首页 > 解决方案 > 如何使用 f{} 将列表转换为不同的格式并在它们之间添加字符串

问题描述

名单如下

second_list = ['C']
first_list =  ['A', 'B']
third_list  = ["D"]

预期结果如下

the firstlist is A,B the second_list is C and thirdlist is D

伪代码

print (f'the firstlist is {j for j in first_list } the second_list is {for j for j in second_list} and thirdlist is {for j for j in third_list')

标签: pythonlistprinting

解决方案


您的伪代码非常接近,但您最好使用string.join它来创建逗号分隔的列表(f 字符串中的表达式可以任意复杂):

second_list = ['C']
first_list =  ['A', 'B']
third_list  = ["D"]

print (f'the firstlist is {",".join(first_list)} the second_list is {",".join(second_list)} and thirdlist is {",".join(third_list)}')

输出:

the firstlist is A,B the second_list is C and thirdlist is D

推荐阅读