我写的一些Python脚本有问题。 Shortinfo:
我有什么: 由包含整数的数组组成的数组:
finalSubLines = [[0,44,52,52,57],[12,154,25,154],[41,42,43,43,74]]
我想从这个程序中得到什么: 迭代所有子数组,对它们进行排序,并删除双值(例如子数组0中的52,子数组1中的154和子数组2中的43)
到目前为止我的脚本:
finalSubLines = [[0,44,52,52,57],[12,154,25,154],[41,42,43,43,74]]
print "\n"
print "list:",finalSubLines,"\n========================"
for i in range (0, len(finalSubLines)):
finalSubLines[i].sort()
print "iterate until index:",len(finalSubLines[i])-2
print "before del-process:",finalSubLines[i]
for j in range (0, len(finalSubLines[i])-2):
print "j=",j
if finalSubLines[i][j] == finalSubLines[i][j+1]:
del finalSubLines[i][j]
print "after del-process:",finalSubLines[i]
print "-------------"
print finalSubLines
这就是我得到的:
问题:
也许有一种更简单的方式来获得我需要的东西,但由于我对脚本编写很新,我不知道更好^^
答案 0 :(得分:3)
easy 方式是使用sets:
[sorted(set(sub)) for sub in finalSubLines]
演示:
>>> finalSubLines = [[0,44,52,52,57],[12,154,25,154],[41,42,43,43,74]]
>>> [sorted(set(sub)) for sub in finalSubLines]
[[0, 44, 52, 57], [12, 25, 154], [41, 42, 43, 74]]
您的循环没有考虑到通过删除项目,您的列表变得越来越短;曾经在索引i + 1
处的内容移至索引i
,但您的循环很乐意转移到索引i + 1
,而值那里曾经位于{ {1}}。因此,您跳过元素。
有关所发生情况的更详细说明,请参阅Loop "Forgets" to Remove Some Items。
答案 1 :(得分:1)
如果您确实要删除完全两次的元素:
finalSubLines = [[0,44,52,52,57],[12,154,25,154],[41,42,43,43,74]]
from collections import Counter
counts = [Counter(sub) for sub in finalSubLines]
print([sorted(k for k,v in c.iteritems() if v != 2) for c in counts])
答案 2 :(得分:0)
试试这个:
tempList=[]
finalSubLines = [[0,44,52,52,57],[12,154,25,154],[41,42,43,43,74]]
for item in finalSubLines:
tempList.append(sorted(set(sorted(item))))
print tempList,