将列表与元组列表进行比较

2024-06-25 23:25:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表,例如

journeylist = [("uk_Frank_3734823","342-2432-242-2342",2,3434-3434),("uk_joe_3734823","342-2432-242-2342",2,3434-3434)]

和一份清单,例如

exclusion = ["joe","jack","alice"]

我想将排除列表与每个元组的0索引进行比较。该值在任何情况下都可以是,例如73473_Jack_uk,并且列表中有jack。他们应该匹配。如果存在匹配项,则必须删除整个元组或将不匹配项添加到另一个列表中


Tags: frank列表情况元组jackjoealiceuk
2条回答

我将通过降低第一个值的大小写并对照它检查exclusion列表来实现这一点:

lowered_exclusion = [excl.lower() for excl in exclusion]
filtered_journeylist = []
for journey in journeylist:
    first = journey[0].lower()
    if not any(excl in first for excl in lowered_exclusion):
        filtered_journeylist.append(journey)

我已经编写了代码并进行了解释,以使事情更清楚。:)

journeylist = [("uk_Frank_3734823","342-2432-242-2342",2,3434-3434),("uk_joe_3734823","342-2432-242-2342",2,3434-3434)] # Your provided journey list;

exclusion = ["joe","jack","alice"] # Your provided exclusion list;

JourneyList_lowercase = [i[0].lower() for i in journeylist] # Dublicate journey list array in lowercase;

ExclusionList_lowercase = [i.lower() for i in exclusion] # Dublicate exclusion list in lowercase;

Filtered_List = [] # Prepare new list;

for JL in JourneyList_lowercase: # Go trough journey list in lowercase array;
    if not any(EXC in JL for EXC in ExclusionList_lowercase): # Check if we have not any exclusion in our journey list;
        Filtered_List.append(JL) # If we have not any exclusion in our journey list -> add value to our new prepared list;
    
print(Filtered_List)

相关问题 更多 >