Python 根据条件从一个列表追加到另一个列表

Python Append from a list to another on a condition

我是 python 新手,我想检查每个列表元素是否存在于另一个列表中(同时尊重索引)并将此元素附加到第三个列表。像这样。如果 'listy'("11-02-jeej") 的第一个元素包含 list_of_dates ("11-02") 的第一个元素,我希望将此元素 "11-02-jeej" 添加到列表列表的第一个列表。下面的代码对我不起作用:(

the output that i want from this code is :[["11-02-jeej"], [2apples], []]
but instead i get : [[], [], []] 

非常感谢!

list_of_dates =["11-02,", "2", "5"]
listy = ["11-02-jeej", "2apples", "d44"]
length = len(list_of_dates)
lst = [[] for m in range(length)]

for i in range(len(list_of_dates)):
    date =  list_of_dates[i]
    for j in range(len(listy)):
         name = listy [j]
    if date in name:
        lst[m].append(name)

print(lst)

您的代码中存在以下问题:

  • 输入的第一个字符串中有一个逗号:“11-02,”。正如您所期望的那样,这是一个前缀,我想尾随的逗号不应该在那里:“11-02”

  • if语句应该内部循环中,因为它需要在那里分配的name变量。

  • m 不是正确的索引。它应该是 i,所以你得到:lst[i].append(name)

下面是您的代码,其中包含这些更正:

list_of_dates =["11-02", "2", "5"]
listy = ["11-02-jeej", "2apples", "d44"]
length = len(list_of_dates)
lst = [[] for m in range(length)]

for i in range(len(list_of_dates)):
    date =  list_of_dates[i]
    for j in range(len(listy)):
        name = listy [j]
        if date in name:
            lst[i].append(name)

print(lst)

请注意,这些循环可以用列表理解来编写:

lst = [[s for s in listy if prefix in s] for prefix in list_of_dates]

请注意,对于给定的示例,“2”也出现在“11-02-jeej”中,因此“11-02”和“2”都匹配,因此这会影响结果。如果您希望“2”仅与“2apples”匹配,那么您可能希望仅在字符串的 start 处测试匹配,使用 .startswith().