1

我正在尝试做一个简单的冒泡排序代码来熟悉列表/字符串操作和方法的使用,但是由于某种原因,当我尝试遍历列表中的每个值以删除空格和非整数值时,它跳过了一些。我什至还没有进入气泡排序部分..

#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', '']
4

5 回答 5

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
于 2009-05-25T02:59:48.340 回答
0

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

于 2009-05-25T02:47:09.117 回答
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))
于 2009-05-25T02:55:22.547 回答
0

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

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

一旦你删除了一个项目,你需要再次遍历列表。

伪代码:

再次:
对于 i = 0 到 list.count - 1
{
  如果条件那么
    删除列表[i]
    再次转到;
}
于 2009-05-25T02:57:07.427 回答
0

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

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

这样您就不会跳过任何列表项,因为缩短列表不会影响任何未来的迭代。当然,上面的代码片段假设 list/array 类支持 deleteItem 方法,并做了适当的事情。

于 2009-05-25T13:39:47.977 回答