-
芜湖不芜
good_tags = ['c#', '.net', 'java']all_tags = [ ['c# .net datetime'], ['c# datetime time datediff relative-time-span'], ['html browser timezone user-agent timezone-offset']]filtered_tags = [[" ".join(filter(lambda tag: tag in good_tags, row[0].split()))] for row in all_tags]print(filtered_tags)输出:[['c# .net'], ['c#'], ['']]>>>
-
慕村9548890
第一条语句:当“x in all_tags”执行时,它将给出 ['c# .net datetime'],它是列表类,而 'c# .net datetime' 是单个字符串,不会单独处理。第二条语句:在第一条语句 x = ['c# .net datetime'] 之后,即列表,现在该列表将在不包含整个列表的 good_tags 中搜索,因此不会返回任何内容。条件 1:如果我们的 good_tags 类似于 ['c#', '.net', 'java', ['c# .net datetime'] ] 那么它将返回 ['c# .net datetime']这是您的解决方案的问题:good_tags = ['c#', '.net', 'java']all_tags = [['c# .net datetime'], ['c# datetime time datediff relative-time-span'], ['html browser timezone user-agent timezone-offset']]#y3 = [x for x in all_tags if x in good_tags]all_tags_refine = []for x in all_tags: y = x[0].split() z = [k for k in y if k in good_tags] all_tags_refine.append(z)print(all_tags_refine)
-
梵蒂冈之花
你的all_tags是一个列表,其中包含三个列表,其中每个列表包含一个字符串。因此,您首先需要做的是将每个子列表转换为包含字符串的列表,而不仅仅是一个字符串。由于那里只有空格,用于分隔标签并且没有逗号,因此您必须将列表从 转换['c# .net datetime']为['c#', '.net', 'datetime']:[x for segments in all_tags[0] for x in segments.split()]然后您可以对整个列表执行此操作,因此迭代它的长度:[[x for segments in all_tags[entry] for x in segments.split()] for entry in range(len(all_tags))]返回:[['c#', '.net', 'datetime'], ['c#', 'datetime', 'time', 'datediff', 'relative-time-span'], ['html', 'browser', 'timezone', 'user-agent', 'timezone-offset']]现在您可以根据您的好标签过滤此列表:y3 = [[x for x in [words for segments in all_tags[entry] for words in segments.split()] if x in good_tags] for entry in range(len(all_tags))]输出:[['c#', '.net'], ['c#'], []]
-
30秒到达战场
good_set = set(good_tags)kept_tags = [[t for t in tags[0].split() if t in good_set] for tags in all_tags]print(kept_tags)# [['c#', '.net'], ['c#'], []]
-
慕标5832272
可能有更好的方法来做到这一点,但就是这样,good_tags = ['c#', '.net', 'java']all_tags = [['c# .net datetime'],['c# datetime time datediff relative-time-span'], ['html browser timezone user-agent timezone-offset']]for tags in all_tags: empty = [] for tag in tags[0].split(" "): if tag in good_tags: empty.append(tag) print(" ".join(empty))
-
慕少森
首先,您没有两个字符串列表。您有字符串列表的列表。good_tags = ['c#', '.net', 'java']all_tags = [['c# .net datetime'],['c# datetime time datediff relative-time-span'], ['html browser timezone user-agent timezone-offset']]all_tags_with_good_tags = []for tags in all_tags: new_good_tags = set() for tag in tags[0].split(): # here you have list, so you need to select 0 element # of it as there's only 1 list element in your example # and then split it on the whitespace to be a list of tags if tag in good_tags: new_good_tags.add(tag) if new_good_tags: all_tags_with_good_tags.append(' '.join(new_good_tags))会得到你['.net c#', 'c#']