鱼C论坛

 找回密码
 立即注册
查看: 1272|回复: 3

[已解决]list列表的一个小问题

[复制链接]
发表于 2020-3-5 00:22:38 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. list1 = [0, 1, 2, 5, 6, 5, 2, 3, 6, 5, 6, 5, 6, 5, 3, 2, 3]
  2. for each in list1:
  3.         if list1.count(each) > 1:
  4.                 list1.remove(each)

  5. print(list1)
复制代码


用这段代码去掉列表中重复的字符,为什么输出结果是这样:
[0, 1, 5, 5, 5, 6, 5, 3, 2, 3]
有的去掉了,有的还在
最佳答案
2020-3-5 01:25:07
本帖最后由 ouyunfu 于 2020-3-5 01:27 编辑

你代码的问题在于索引在变,列表也在变,有些元素直接被跳过了。运行以下代码应该 可以加深理解
  1. # -*- coding: utf-8 -*-
  2. list1 = [0, 1, 2, 5, 6, 5, 2, 3, 6, 5, 6, 5, 6, 5, 3, 2, 3]
  3. for each in list1:#list1在变
  4.     print((list1.index(each),each))
  5.     if list1.count(each) > 1:
  6.         list1.remove(each)
  7.         print(list1)
  8. print('#####################################################')
  9. list1 = [0, 1, 2, 5, 6, 5, 2, 3, 6, 5, 6, 5, 6, 5, 3, 2, 3]
  10. for each in list1[:]:#list1[:]不变
  11.     print((list1.index(each),each))
  12.     if list1.count(each) > 1:
  13.         list1.remove(each)
  14.         print(list1)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-3-5 00:28:18 | 显示全部楼层
转成集合,再转回来就行了。
>>> list1 = [0, 1, 2, 5, 6, 5, 2, 3, 6, 5, 6, 5, 6, 5, 3, 2, 3]
>>> list1 = set(list1)
>>> list1
{0, 1, 2, 3, 5, 6}
>>> list1 = list(list1)
>>> list1
[0, 1, 2, 3, 5, 6]


用你的方法得2个表


list1 = [0, 1, 2, 5, 6, 5, 2, 3, 6, 5, 6, 5, 6, 5, 3, 2, 3]
for each in list1[:]:
        if list1.count(each) > 1:
                list1.remove(each)

print(list1)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-5 01:25:07 | 显示全部楼层    本楼为最佳答案   
本帖最后由 ouyunfu 于 2020-3-5 01:27 编辑

你代码的问题在于索引在变,列表也在变,有些元素直接被跳过了。运行以下代码应该 可以加深理解
  1. # -*- coding: utf-8 -*-
  2. list1 = [0, 1, 2, 5, 6, 5, 2, 3, 6, 5, 6, 5, 6, 5, 3, 2, 3]
  3. for each in list1:#list1在变
  4.     print((list1.index(each),each))
  5.     if list1.count(each) > 1:
  6.         list1.remove(each)
  7.         print(list1)
  8. print('#####################################################')
  9. list1 = [0, 1, 2, 5, 6, 5, 2, 3, 6, 5, 6, 5, 6, 5, 3, 2, 3]
  10. for each in list1[:]:#list1[:]不变
  11.     print((list1.index(each),each))
  12.     if list1.count(each) > 1:
  13.         list1.remove(each)
  14.         print(list1)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2020-3-5 08:21:25 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-3 07:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表