6 回答

TA貢獻1796條經驗 獲得超7個贊
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#'], ['']]
>>>

TA貢獻1884條經驗 獲得超4個贊
第一條語句:當“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)

TA貢獻1900條經驗 獲得超5個贊
你的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#'], []]

TA貢獻1828條經驗 獲得超6個贊
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#'], []]

TA貢獻1966條經驗 獲得超4個贊
可能有更好的方法來做到這一點,但就是這樣,
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))

TA貢獻2019條經驗 獲得超9個贊
首先,您沒有兩個字符串列表。您有字符串列表的列表。
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#']
添加回答
舉報