【问题标题】:How to combine the elements of two list如何组合两个列表的元素
【发布时间】:2021-10-31 21:16:00
【问题描述】:

我有两个列表

List1 = ['foo', 'bar', '.txt']
List2 = [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]

我希望输出是

output = ['foo1bar3.txt', 'foo1bar4.txt', 'foo1bar5.txt', 'foo2bar3.txt', 'foo2bar4.txt', 'foo2bar5.txt'] 

【问题讨论】:

  • zip 实际上是这里的重点。
  • @schwobaseggl 但itertools.zip_longest 不是:D
  • @timgeb hmm.. 我可以在这里使用任何压缩的唯一方法是一遍又一遍地循环通过可迭代的生成 List1。但是,我可以使用普通的zip
  • 如果您不必在 5 分钟后盯着自己的代码,那您就做错了:D

标签: python list arraylist


【解决方案1】:

不硬编码元素数量的一种:

output = ['%d'.join(List1) % x for x in List2]

Try it online!

【讨论】:

  • 谢谢。你能解释一下'%d'和%在做什么吗?
  • @ramit 只是将数字元组格式化为连接的字符串。见docs.python.org/3/library/…
【解决方案2】:
list1 = ['foo', 'bar', '.txt']
list2 = [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
list3 = []

for x, y in list2:

    list3.append(list1[0] + str(x) + list1[1] + str(y) + list1[2])

print(list3)

输出

['foo1bar3.txt', 'foo1bar4.txt', 'foo1bar5.txt', 'foo2bar3.txt', 'foo2bar4.txt', 'foo2bar5.txt']

【讨论】:

    【解决方案3】:

    使用list comprehensionstring formatting

    a, b, c = List1
    output = [f"{a}{x}{b}{y}{c}" for x, y in List2]
    # ['foo1bar3.txt', 'foo1bar4.txt', 'foo1bar5.txt', 'foo2bar3.txt', 'foo2bar4.txt', 'foo2bar5.txt']
    

    【讨论】:

    • 它给了我一个错误- ValueError: too many values to unpack (expected 3)
    • 非常感谢。是的,它现在工作得很好。
    • 你们这些人拥有花哨的现代字符串格式......忽略了五年前对你来说显而易见的事情:-)
    猜你喜欢
    • 2020-07-19
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    相关资源
    最近更新 更多