我有兩個串列,一個帶有單詞,另一個帶有這樣的單詞型別
['fish', 'Robert', 'dog', 'ball', 'cat', 'dog', 'Robert']
['animal', 'person', 'animal', 'object', 'animal', 'animal', 'person']
我需要洗掉第一個串列中的重復項,并洗掉與洗掉的單詞相同的索引處的型別。
最后我需要這樣的東西:
['fish', 'Robert', 'dog', 'ball', 'cat']
['animal', 'person', 'animal', 'object', 'animal']
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
使用字典會更容易(見下文)
有清單
list1 = ['fish', 'Robert', 'dog', 'ball', 'cat', 'dog', 'Robert']
list2 = ['animal', 'person', 'animal', 'object', 'animal', 'animal', 'person']
new_list1 = []
new_list2 = []
for a, b in zip(list1, list2):
if a not in new_list1:
new_list1.append(a)
new_list2.append(b)
print(new_list1)
print(new_list2)
輸出:
['fish', 'Robert', 'dog', 'ball', 'cat']
['animal', 'person', 'animal', 'object', 'animal']
用字典
x = dict(zip(
['fish', 'Robert', 'dog', 'ball', 'cat', 'dog', 'Robert'],
['animal', 'person', 'animal', 'object', 'animal', 'animal', 'person']
))
print(x)
print(list(x.keys()))
print(list(x.values()))
輸出:
{'fish': 'animal', 'Robert': 'person', 'dog': 'animal', 'ball': 'object', 'cat': 'animal'}
['fish', 'Robert', 'dog', 'ball', 'cat']
['animal', 'person', 'animal', 'object', 'animal']
uj5u.com熱心網友回復:
只需回圈并使用 zip 功能
腳本
# Input Vars
a = ['fish', 'Robert', 'dog', 'ball', 'cat', 'dog', 'Robert']
b = ['animal', 'person', 'animal', 'object', 'animal', 'animal', 'person']
# Output Vars
c = []
d = []
# Process
for e, f in zip(a, b):
if(e not in c):
c.append(e)
d.append(f)
# Print Output
print(c)
print(d)
輸出
['fish', 'Robert', 'dog', 'ball', 'cat']
['animal', 'person', 'animal', 'object', 'animal']
uj5u.com熱心網友回復:
您可以使用 zip 兩個串列并使用dictionary鍵只能重復一次的想法,然后將鍵和值作為您想要的兩個串列回傳:
lst1 = ['fish', 'Robert', 'dog', 'ball', 'cat', 'dog', 'Robert']
lst2 = ['animal', 'person', 'animal', 'object', 'animal', 'animal', 'person']
res = dict(zip(lst1, lst2))
# res -> {'Robert': 'person','ball': 'object', 'cat': 'animal', 'dog': 'animal', 'fish': 'animal'}
list(res.keys())
# ['fish', 'Robert', 'dog', 'ball', 'cat']
list(res.values())
# ['fish', 'Robert', 'dog', 'ball', 'cat']
uj5u.com熱心網友回復:
您可以使用 aset進行重復資料洗掉,然后使用index僅從word_type串列中獲取第一個匹配項
word = ['fish', 'Robert', 'dog', 'ball', 'cat', 'dog', 'Robert']
word_type = ['animal', 'person', 'animal', 'object', 'animal', 'animal', 'person']
unique_word = list(set(word))
updated_word_type = [word_type[word.index(_)] for _ in unique_word]
輸出
# unique_word
['dog', 'fish', 'Robert', 'ball', 'cat']
# updated_word_type
['animal', 'animal', 'person', 'object', 'animal']
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/491947.html
上一篇:如何在Linux上檢測塊設備?
