首页 > 解决方案 > 仅当单词的一部分不在列表中时才附加

问题描述

我有一个类似下面的列表,并想从中列出两个列表。如果第一个包含 S01_a,则 S01_b 应该在第二个列表中。

my_list = ['S01_a', 'S01_b', 'S02_a', 'S02_b', 'S03_a', 'S03_b', 'S04_a', 'S04_b']

我试过这个,但我不知道如何引用 list1 中项目的 [1:2] 字符。有没有人有解决方案?

stims = ["S01_a", "S01_b", "S02_a", "S02_b", "S03_a", "S03_b", "S04_a", "S04_b"]

l1 = []
l2 = []
for item in stims:
    if item[1:2] not in l1:
        l1.append(item)
    else:
        l2.append(item)


print(l1)
print(l2)

输出是:

['S01_a', 'S01_b', 'S02_a', 'S02_b', 'S03_a', 'S03_b', 'S04_a', 'S04_b']
[]

先感谢您。

标签: pythonlistcharacter

解决方案


You can use any() with a generator that tests item[1:3] against each element of the list.

for item in stims:
    if not any(item[1:3] == el[1:3] for el in l1):
        l1.append(item)
    else:
        l2.append(item)

You need to use the slice [1:3]. Remember, the second index is not inclusive, so [1:2] just selects the digit 0, not the two digits 01, 02, etc.


推荐阅读