我有两个字符串列表如下:
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_tag’中字符串列表中的'good_tags‘,
我尝试使用“in”而不是“not in”,基于Remove all the elements that occur in one list from another
y3 = [x for x in all_tags if x in good_tags]
print ('y3: ', y3)
y4 = [x for x in good_tags if x in all_tags]
print ('y4: ', y4)退出:
y3: []
y4: []发布于 2020-09-24 09:58:21
第一语句:当"x in all_tags“执行时,它将给出'c# .net datetime‘,即list类,而'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)发布于 2020-09-24 09:45:33
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#'], ['']]
>>> 发布于 2020-09-24 09:30:56
首先,您没有两个字符串列表。您有字符串列表。
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#']https://stackoverflow.com/questions/64043458
复制相似问题