3 回答

TA貢獻(xiàn)1816條經(jīng)驗 獲得超6個贊
words您可以將with模塊的元素組合起來itertools chain,然后使用 set() 方法來消除所有重復(fù)項:
import itertools
words = ['1,2,3,4','5,7,8,4','1,2,3,9']
c = list(set(itertools.chain(words[0].replace(',',''),words[1].replace(',',''),words[2].replace(',',''))))
new_words = [int(x) for x in c]
new_words.sort()
print(new_words)
結(jié)果
[1, 2, 3, 4, 5, 7, 8, 9]
對于更新
import itertools
words = ["apple is not good", "mongo is delicious", "banana is very good"]
new_words = list(set(itertools.chain(words[0].split(' '), words[1].split(' '), words[2].split(' '))))
print(new_words)
結(jié)果
['not', 'mongo', 'is', 'apple', 'good', 'very', 'delicious', 'banana']

TA貢獻(xiàn)2036條經(jīng)驗 獲得超8個贊
words = ['1,2,3,4',
'5,7,8,4',
'1,2,3,9']
new_list = []
for w in words :
for i in map(int, w.split(',')):
if i not in new_list:
new_list.append(i)
print(new_list)
訣竅是從列表中的每個單詞中提取數(shù)字。每個word都是由逗號分隔的一系列數(shù)字。因此,w.split(',')將每個以逗號分隔的數(shù)字字符串拆分為一個列表。該map()函數(shù)將該int()方法應(yīng)用于每個數(shù)字字符串,將其轉(zhuǎn)換為數(shù)值。然后,如果該值尚不存在,則將其添加到 new_list 中。
此解決方案還處理大于 9 的數(shù)字。
另外,舉個例子來幫助理解map:
"1,2,3,4".split(",") --> ["1", "2", "3", "4"]
和
map(int, ["1", "2", "3", "4"]) --> [1, 2, 3, 4]

TA貢獻(xiàn)1846條經(jīng)驗 獲得超7個贊
You need to use extend, not append. And also split each line. Convert to "set" to remove duplicate items
words = ['1,2,3,4',
'5,7,8,4',
'1,2,3,9']
new_list = []
for i in words :
new_list.extend(i.split(','))
new_list = list(set(new_list))
new_list.sort()
print(new_list)
或者
保持元素的順序
words=['apple,banana,orange', 'apple, mango']
new_list = []
for i in words :
new_list.extend(i.split(','))
result =[]
for i in new_list:
if i not in result:
result.append(i)
print(result)
添加回答
舉報