我需要一些python列表的帮助。
file_data=["today is good","happiness is very nice", "i am hungry","i need to go to gym"]
file_names=["_podcast_podcast_2","article_about_happiness","podcast_podcast_34","article about fitness"]
我需要删除与"播客"相关的元素。如果podcast出现在file_names中,则删除该元素并删除file_data的相应元素。
必需的输出:
file_data=["happiness is very nice", "i need to go to gym"]
file_names=["article_about_happiness","article about fitness"]
答案 0 :(得分:3)
file_data, file_names = zip(
*(i for i in zip(file_data, file_names) if 'podcast' not in i[-1])
)
说明:
zip
的工作方式。if "substring" not in "string"
。zip(*list)
)。我将它们分配给了初始变量。答案 1 :(得分:1)
使用列表理解的简单单行:
file_names, file_data = [[f, file_data[i]] for i, f in enumerate(file_names) if "podcast" not in f]
输出:
['article about fitness', 'i need to go to gym']
['article_about_happiness', 'happiness is very nice']
我意识到我可能误读了最初的问题,并且错误地输出了输出。这是一个导致问题中列出的输出的版本:
grouped = [[file_names[i], file_data[i]] for i,f in enumerate(file_names) if "podcast" not in file_names[i]]
file_names = [i[0] for i in grouped]
file_data = [i[1] for i in grouped]
print(file_data)
print(file_names)
输出:
['happiness is very nice', 'i need to go to gym']
['article_about_happiness', 'article about fitness']