我在这个冒泡排序代码中找不到逻辑错误

时间:2009-05-25 02:41:25

标签: string parsing list python-3.x

我正在尝试使用简单的冒泡排序代码来熟悉list / string manip&方法使用,但由于某种原因,当我尝试遍历列表中的每个值以删除空白和非int的值时,它会跳过一些。我甚至没有进入泡沫分类部分..

#test data:  45,5j, f,e,s , , , 45,q,

    if __name__ == "__main__":
getList = input("Enter numbers separated by commas:\n").strip()
listOfBubbles = getList.split(',')
print (listOfBubbles)
i = 0
for k in listOfBubbles:
    listOfBubbles[i] = k.strip()
    print ("i = {0} -- Checking '{1}'".format(i,listOfBubbles[i]))
    if listOfBubbles[i] == '' or listOfBubbles[i] == ' ':
        del listOfBubbles[i]
        i -= 1
    else:
        try:
            listOfBubbles[i] = int(listOfBubbles[i])
        except ValueError as ex:
            #print ("{0}\nCan only use real numbers, deleting '{1}'".format(ex, listOfBubbles[i]))
            print ("deleting '{0}', i -= 1".format(listOfBubbles[i]))
            del listOfBubbles[i]
            i -= 1
        else:
            print ("{0} is okay!".format(listOfBubbles[i]))
    i += 1

print(repr(listOfBubbles))

输出:

    Enter numbers separated by commas:
45,5j, f,e,s , , , 45,q,
['45', '5j', ' f', 'e', 's ', ' ', ' ', ' 45', 'q', '']
i = 0 -- Checking '45'
45 is okay!
i = 1 -- Checking '5j'
deleting '5j', i -= 1
i = 1 -- Checking 'e'
deleting 'e', i -= 1
i = 1 -- Checking ''
i = 1 -- Checking '45'
45 is okay!
i = 2 -- Checking 'q'
deleting 'q', i -= 1
[45, 45, ' ', ' 45', 'q', '']

5 个答案:

答案 0 :(得分:1)

如何更加pythonic方式?

#input
listOfBubbles = ['45', '5j', ' f', 'e', 's ', ' ', ' ', ' 45', 'q', '']
#Copy input, strip leading / trailing spaces. Remove empty items
stripped = [x.strip() for x in listOfBubbles if x.strip()]    

# list(filtered) is ['45', '5j', 'f', 'e', 's', '45', 'q']
out = []
for val in filtered:
  try:
    out.append(int(val))
  except:
    # don't do anything here, but need pass because python expects at least one line
    pass 
# out is [45, 45]

最后,跳到正确的答案

out.sort()

更新 澄清传递

>>> for i in range(0,5):
        pass
        print i

0
1
2
3
4

答案 1 :(得分:0)

永远不要改变你循环的列表 - 在循环for k in listOfBubbles:内,你要删除那个列表中的一些项目,这会扰乱内部循环逻辑。有许多替代方法,但最简单的解决方法是在要更改的列表的副本上循环:for k in list(listOfBubbles):。可能会有更多问题,但这是第一个问题。

答案 2 :(得分:0)

没关系,修好了。我将循环从for ...更改为while ..

if __name__ == "__main__":
    getList = input("Enter numbers separated by commas:\n").strip()
    listOfBubbles = getList.split(',')
    print (listOfBubbles)
    i = 0
    while i < len(listOfBubbles):
        listOfBubbles[i] = listOfBubbles[i].strip()
        print ("i = {0} -- Checking '{1}'".format(i,listOfBubbles[i]))
        if listOfBubbles[i] == '' or listOfBubbles[i] == ' ':
            del listOfBubbles[i]
            i -= 1
        else:
            try:
                listOfBubbles[i] = int(listOfBubbles[i])
            except ValueError as ex:
                #print ("{0}\nCan only use real numbers, deleting '{1}'".format(ex, listOfBubbles[i]))
                print ("deleting '{0}', i -= 1".format(listOfBubbles[i]))
                del listOfBubbles[i]
                i -= 1
            else:
                print ("{0} is okay!".format(listOfBubbles[i]))
        i += 1

    print(repr(listOfBubbles))

答案 3 :(得分:0)

您不能使用迭代器从列表中删除,因为长度会发生变化。

相反,您必须在for循环(或while循环)中使用索引。

删除项目后,您需要再次遍历列表。

伪代码:

again:
for i = 0 to list.count - 1
{
  if condition then 
    delete list[i] 
    goto again;
}

答案 4 :(得分:0)

如果您要在迭代时从列表中删除,请按相反的顺序遍历列表:

for( i = myList.length - 1; i >= 0; i-- ) {
   // do something
   if( some_condition ) {
      myList.deleteItem( i );
   }
}

这样您就不会跳过任何列表项,因为缩短列表不会影响将来的任何迭代。当然,上面的代码段假定列表/数组类支持deleteItem方法并执行相应的操作。