简体   繁体   English

基于元组列表创建新列表

[英]Creating a new list based on lists of tuples

Let's assume there is a list of tuples:假设有一个元组列表:

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

and it returns它返回

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

And I have created two other lists containing certain elements from the x.something():我还创建了另外两个列表,其中包含 x.something() 中的某些元素:

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

So I want to assign the tuples from x.something() to a new list based on y and z by所以我想将 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')

What I would like to have is the newlist looks like:我想要的是新列表看起来像:

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

But I've got但我有

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

What went wrong and how to fix it?出了什么问题以及如何解决?

I think you want to get if something in y instead of if something in 'y' because they are two seperate lists, not strings:我想你想得到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')

try this:试试这个:

t = [('a', 'b'),
('c', 'd'),
('e', 'f'),
('g', 'h'),
('i', 'j')]

y = [('a', 'b'), ('c', 'd')]
z = [('e', 'f'), ('g', 'h')]
new_list = []
for x in t:
    if x in y:
        new_list.append('color1')
    elif x in z:
        new_list.append('color2')
    else:
        new_list.append('color3')
print(new_list)

output: output:

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

You should remove the quotes from if something in 'y' because it assumes that you're checking if something is in the string 'y' .您应该删除 if something if something in 'y'中的引号,因为它假定您正在检查字符串'y'中是否有内容。 Same for z . z一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM