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

后端 未结 4 895
难免孤独
难免孤独 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.

    0 讨论(0)
  • 2020-12-21 10:20
    for e in range(len(List)):
        for p in range(len(List[e])):
            List[e][p] = int(List[e][p])
    

    Or, you could create a new list:

    New = [list(map(int, sublist)) for sublist in List]
    
    0 讨论(0)
  • 2020-12-21 10:32

    Nested list comprehension is the best solution, but you can also consider map with lambda function:

    lista = [['1','2','3'],['8','6','8'],['2','9','3'],['2','5','7'],['5','4','1'],['0','8','7']]
    
    new_list = map(lambda line: [int(x) for x in line],lista)
    # Line is your small list.
    # With int(x) you are casting every element of your small list to an integer
    # [[1, 2, 3], [8, 6, 8], [2, 9, 3], [2, 5, 7], [5, 4, 1], [0, 8, 7]]
    
    0 讨论(0)
  • 2020-12-21 10:35

    You can use a nested list comprehension:

    converted = [[int(num) for num in sub] for sub in lst]
    

    I also renamed list to lst, because list is the name of the list type and not recommended to use for variable names.

    0 讨论(0)
提交回复
热议问题