首页 > 解决方案 > 基于元组列表创建新列表

问题描述

假设有一个元组列表:

for something in x.something()
    print(something)

它返回

('a', 'b')
('c', 'd')
('e', 'f')
('g', 'h')
('i', 'j')

我还创建了另外两个列表,其中包含来自 x.something() 的某些元素:

y = [('a', 'b'), ('c', 'd')]
z = [('e', 'f'), ('g', 'h')]

所以我想将 x.something() 中的元组分配给基于 y 和 z 的新列表

newlist = []
for something in x.something():
    if something in 'y':
        newlist.append('color1')
    elif something in 'z':
        newlist.append('color2')
    else:
        newlist.append('color3')

我想要的是新列表看起来像:

['color1', 'color1', 'color2', 'color2', 'color3']

但我有

TypeError: 'in <string>' requires string as left operand, not tuple

出了什么问题以及如何解决?

标签: pythonlist

解决方案


我认为你想得到if something in y而不是if something in 'y'因为它们是两个单独的列表,而不是字符串:

newlist = []
for something in x.something():
    if something in y:
        newlist.append('color1')
    elif something in z:
        newlist.append('color2')
    else:
        newlist.append('color3')

推荐阅读