Reputation: 380
nested_list = [['bob', '444'], ['steve', '111'], ['mark', '888']]
I want to convert the second element in each nested list to the int type. I am trying something like this
nested_list2 = []
[int(x[1]) for x in nested_list]
this does convert the second element to int, but i lose the rest of the data.
I've also tried this, but it colapses my nested list structure:
[nested_list2.extend((x[0], int(x[1]))) for x in testlist]
Is it possible here to end up with something like the following
nested_list2 = [['bob', 444], ['steve', 111], ['mark', 888]]
Upvotes: 2
Views: 1089
Reputation: 26
nested_list2=[]
temp=[]
for i in nested_list:
for j in i:
temp.append(j)
nested_list2.append(temp)
temp=[]
for i in nested_list2:
i[1]=int(i[1])
Try this and let me know if it is what you needed. Cheers!
Upvotes: 0
Reputation: 368
nested_list = [['bob', '444'], ['steve', '111'], ['mark', '888']]
for x in nested_list:
x[1]=int(x[1])
Upvotes: 3
Reputation: 164643
A list comprehension should be used to create a new list, not modify an existing list in place:
nested_list = [['bob', '444'], ['steve', '111'], ['mark', '888']]
res = [[name, int(num)] for name, num in nested_list]
# [['bob', 444], ['steve', 111], ['mark', 888]]
Upvotes: 4