Home > Enterprise >  How can I turn the items within a list that is within another list, turn them from char to ints
How can I turn the items within a list that is within another list, turn them from char to ints

Time:12-09

[['1', '1'], ['1', '2'], ['1', '3'], ['1', '4'], ['2', '1'], ['2', '2'], ['2', '5'], ['3', '3'], ['3', '4'], ['3', '6'], ['4', '5'], ['5', '6']]

This is what I'm getting but I am trying to return:

[[1,1], [1,2], [1,3], [1,4]...etc

My code to take each line of the file:

##takes each line of the text file
filename = input("Enter filename:")
with open(filename) as file_in:
    lines = []
    for line in file_in:
        words = line.split()
        lines.append(words)

CodePudding user response:

Iterate through each of the "words" and cast them as an int using something like int(word). Be aware, his could throw exceptions if the string isn't formatted as an int, so it would be wise to include a try/catch

CodePudding user response:

Itterrate through sublist and type to int .

nested = [['1', '1'], ['1', '2'], ['1', '3'], ['1', '4'], ['2', '1'], ['2', '2'], ['2', '5'], ['3', '3'], ['3', '4'], ['3', '6'], ['4', '5'], ['5', '6']]

final = [[int(e) for e in item] for item in nested]
print(final)

Gives #

[[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [2, 5], [3, 3], [3, 4], [3, 6], [4, 5], [5, 6]]

CodePudding user response:

The remove() method removes the first matching element which is passed as an argument from the list the pop() method removes an element at a given index and will als0 the removed the item.

  • Related