如何将两个列表的字符串两两拼接并添加'or'生成目标格式输出?
实现方法
你可以先生成所有两两拼接的组合,再用" or "将它们连接起来,这样能避免嵌套循环直接打印导致的末尾多余or问题,分两种格式实现:
带引号的格式
a = ["new", "york"] b = ["spring", "summer", "autumn"] # 生成所有带引号的拼接组合 quoted_combinations = [f'"{x} {y}"' for x in a for y in b] # 用" or "连接所有元素 result_with_quotes = " or ".join(quoted_combinations) print(result_with_quotes)
输出结果:
"new spring" or "new summer" or "new autumn" or "york spring" or "york summer" or "york autumn"
不带引号的格式
a = ["new", "york"] b = ["spring", "summer", "autumn"] # 生成所有不带引号的拼接组合 unquoted_combinations = [f"{x} {y}" for x in a for y in b] # 用" or "连接所有元素 result_without_quotes = " or ".join(unquoted_combinations) print(result_without_quotes)
输出结果:
new spring or new summer or new autumn or york spring or york summer or york autumn
如果坚持用嵌套循环实现,也可以先把所有组合存入列表,最后统一连接(避免循环内打印产生多余or):
a = ["new", "york"] b = ["spring", "summer", "autumn"] temp_list = [] for x in a: for y in b: temp_list.append(f"{x} {y}") # 带引号就改成f'"{x} {y}"' print(" or ".join(temp_list))
内容的提问来源于stack exchange,提问作者Breetlee
相关产品推荐
相关产品推荐

