List of list, converting all strings to int, Python 3

后端 未结 4 896
难免孤独
难免孤独 2020-12-21 09:38

I am trying to convert all elements of the small lists in the big list to integers, so it should look like this:

current list:
list = [[\'1\',\'2\',\'3\'],[\         


        
4条回答
  •  轮回少年
    2020-12-21 10:19

    In short, you are not mutating lst:

    for e in lst:
        for i in e:
            # do stuff with i
    

    is the equivalent of

    for e in lst:
        for n in range(len(e)):
            i = e[n]  # i and e[n] are assigned to the identical object
            # do stuff with i
    

    Now, whether the "stuff" you are doing to i is reflected in the original data, depends on whether it is a mutation of the object, e.g.

    i.attr = 'value'  # mutation of the object is reflected both in i and e[n]
    

    However, string types (str, bytes, unicode) and int are immutable in Python and variable assignment is not a mutation, but a rebinding operation.

    i = int(i)  
    # i is now assigned to a new different object
    # e[n] is still assigned to the original string
    

    So, you can make your code work:

    for e in lst:
        for n in range(len(e)):
            e[n] = int(e[n])
    

    or use a shorter comprehension notation:

     new_lst = [[int(x) for x in sub] for sub in lst]
    

    Note, however, that the former mutates the existing list object lst, while the latter creates a new object new_lst leaving the original unchanged. Which one you choose will depend on the needs of your program.

提交回复
热议问题