1

Python noob here. I have a list of numbers represented as strings. Single digit numbers are represented with a zero and I'm trying to get rid of the zeroes. For instance, ['01', '21', '03'] should be ['1', '21', '3'].

My current solution seems a bit clumsy:

for item in list:  
    if item[0] == '0':     
        list[list.index(item)] = item[1]

I'm wondering why this doesn't work:

for item in list:  
    if item[0] == '0':  
        item = item[1]
4

4 に答える 4

4

Rebinding the iterating name does not mutate the list.

Also:

>>> [str(int(x, 10)) for x in ['01', '21', '03']]
['1', '21', '3']
于 2012-07-18T02:41:26.583 に答える
3

You could try stripping the zero:

>>> map(lambda x: x.lstrip('0'), ['001', '002', '030'])
['1', '2', '30']
于 2012-07-18T02:44:23.777 に答える
3

リストを変更するには:

for i, item in enumerate(mylist):  
    if item.startswith('0'):     
        mylist[i] = item[1:]

おそらく、新しいリストを作成するだけの方がよいでしょう:

new_list = [x.lstrip('0') for x in mylist]

への割り当てitemは名前itemに新しい値を与えるだけで、 の古い値には何もしないため、コードは機能しませんitem

于 2012-07-18T02:48:11.667 に答える
-1

The code "item" is a variable that contains the value of the item as you iterate through the list. It has no reference to the list itself.

Your first solution is very slow because it will have to search the list for each item to find the index.

See other answers for examples of how to accomplish what you want.

于 2012-07-18T02:45:12.123 に答える