【问题标题】:combining three list into one list [duplicate]将三个列表合并为一个列表[重复]
【发布时间】:2020-11-26 07:05:28
【问题描述】:

这是我合并三个列表的代码。

one=['nlo_90', 'nhi_76', 'nhi_88']
two=['12', '44', '84']
three=[['a','a','b','c'], ['g','a','g','g'], ['b','g','g','b']]
new_three=[list(dict.fromkeys(q)) for q in three]

z=zip(one,two,new_three)
for a,b,c in z:
    print(f'a:{a},\tb:{b},\tc:{c}')

下面是输出:

a:nlo_90,   b:12,   c:['a', 'b', 'c']
a:nhi_76,   b:44,   c:['g', 'a']
a:nhi_88,   b:84,   c:['b', 'g']

我想要的输出是:

a:nlo_90,   b:12,   c:a, b, c
a:nhi_76,   b:44,   c:g, a
a:nhi_88,   b:84,   c:b, g

【问题讨论】:

  • ", ".join(c) ?
  • 不是您要求的,但考虑使用 set 而不是您的 dict 方法从 three 中删除重复项。 new_three = [set(q) for q in three].
  • 从组件部分构建字符串可从任何有关字符串的教程中获得。我们希望您在此处发布之前进行基础研究。你在哪里被这些材料困住了?

标签: python list


【解决方案1】:

只需将列表转换为以', ' 作为内部分隔符的连接字符串。目前,它正在打印完整列表:['a', 'b', 'c']

使用', '.join(c) 将获取列表中的每个项目,并将', ' 作为组合字符串放在它们之间。由于您的项目是字符串,因此在组合过程中没有任何转换,因此最终输出为:a, b, c

for a, b, c in z:
    c_str = ', '.join(c)
    print(f'a:{a},\tb:{b},\tc:{c_str}')

【讨论】:

    猜你喜欢
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 2014-05-16
    • 2018-04-10
    相关资源
    最近更新 更多