简体   繁体   English

如果列表包含一个项目,则列表等于项目

[英]If list contains an item, then list equals to item

I don't know how to formulate the question correctly: I have a list of lists, which contains multiple items.我不知道如何正确地提出问题:我有一个列表列表,其中包含多个项目。

mylist=[['a','b','c','₾'],['x','t','f','₾'],['a','d'],['r','y'],['c','₾'],['a','b','c','i'],['h','j','l','₾']]

If any of the lists contains symbol '₾', I want to append the symbol to another list, else append None.如果任何列表包含符号“₾”,我想将 append 符号添加到另一个列表,否则 append 无。

result=[]
for row in mylist:
    for i in row:
        if i=='₾':
            result.append(i)
        else:
            result.append(None)
result

But I want to get this result:但我想得到这个结果:

result=['₾','₾',None,None,'₾',None,'₾']

That would be:那将是:

result = ['₾' if '₾' in sublist else None for sublist in mylist]
result = []
for row in mylist:
    if '₾' in row:
        result.append('₾')
    else:
        result.append(None)
>>> mylist=[['a','b','c','₾'],['x','t','f','₾'],['a','d'],['r','y'],['c','₾'],['a','b','c','i'],['h','j','l','₾']]
>>> c = '₾'
>>> [c if c in row else None for row in mylist]
['₾', '₾', None, None, '₾', None, '₾']

That is, you can use a list comprehension: for each list in mylist , use ₾ if it is in the list, or else None :也就是说,您可以使用列表理解:对于mylist中的每个列表,如果它在列表中则使用 ₾ ,否则使用None

c = '₾'
result = [c if c in row else None for row in mylist]

There were several problems with the loop in the posted code:发布的代码中的循环存在几个问题:

  • After finding a ₾, the inner loop should break, stop searching the rest找到 ₾ 后,内循环应该中断,停止搜索 rest
  • The value should only be None when all values were not ₾只有当所有值都不是 ₾ 时,该值才应为None

Here's one way to fix the loop:这是修复循环的一种方法:

result = []
for row in mylist:
    for item in row:
        if item == '₾':
            result.append(item)
            break
    else:
        result.append(None)

Notice here that else belongs to the inner for , not the if .注意这里else属于内部for ,而不是if The meaning of this is that if the inner loop never reached a break , then this else will be executed.这意味着如果内循环从未到达break ,那么else将被执行。 This fixes both of the problems I mentioned earlier.这解决了我之前提到的两个问题。

A small edit to your code can be done to get the desired result可以对您的代码进行少量编辑以获得所需的结果

mylist=[['a','b','c','₾'],['x','t','f','₾'],['a','d'],['r','y'],['c','₾'],['a','b','c','i'],['h','j','l','₾']]

result=[]
for row in mylist:
    if '₾' in row:
        result.append(i)
    else:
        result.append(None)
result

Output Output

['₾', '₾', None, None, '₾', None, '₾']

The above code can be reduced into a line of List Comprehension上面的代码可以简化成一行List Comprehension

['₾' if '₾' in row else None for row in mylist]

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

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