为了账号安全,请及时绑定邮箱和手机立即绑定

如何删除列表中的重复数字(Python)?

如何删除列表中的重复数字(Python)?

SMILET 2023-08-22 18:02:28
我有一个清单:words = ['1,2,3,4',         '5,7,8,4',         '1,2,3,9']我的目标是根据单词创建一个新列表,但不包含重复的数字。这是我想要的一个例子!new_list=[1,2,3,4,5,7,8,9]我做到了 :words = ['1,2,3,4',         '5,7,8,4',         '1,2,3,9']new_list = []for i in words :    if i not in new_list:        new_list.append(i)print(new_list)但我的列表中再次出现相同的数字:['1,2,3,4', '5,7,8,4', '1,2,3,9']编辑 :我想做同样的事情,但用真实的语言,比如:[" apple is not good",  "mongo is delicious",  banana is very good"] 我的新名单必须是这些短语中的每一个单词都是独一无二的。这是我想要的结果的示例:["apple,is,not,good,mongo,delicious,banana,very"]正如您所看到的,我只从列表的短语中获得了唯一的单词。
查看完整描述

3 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

words您可以将with模块的元素组合起来itertools chain,然后使用 set() 方法来消除所有重复项:


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)

结果


[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)

结果


['not', 'mongo', 'is', 'apple', 'good', 'very', 'delicious', 'banana']


查看完整回答
反对 回复 2023-08-22
?
慕桂英3389331

TA贡献2036条经验 获得超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)

诀窍是从列表中的每个单词中提取数字。每个word都是由逗号分隔的一系列数字。因此,w.split(',')将每个以逗号分隔的数字字符串拆分为一个列表。该map()函数将该int()方法应用于每个数字字符串,将其转换为数值。然后,如果该值尚不存在,则将其添加到 new_list 中。


此解决方案还处理大于 9 的数字。


另外,举个例子来帮助理解map:


"1,2,3,4".split(",") --> ["1", "2", "3", "4"]


map(int, ["1", "2", "3", "4"]) --> [1, 2, 3, 4]


查看完整回答
反对 回复 2023-08-22
?
喵喵时光机

TA贡献1846条经验 获得超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)


查看完整回答
反对 回复 2023-08-22
  • 3 回答
  • 0 关注
  • 185 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信