Home > Mobile >  How to Convert a nested list with strings to a list with strings and ints
How to Convert a nested list with strings to a list with strings and ints

Time:10-27

This is My current output for a Grocery list Code. The list is setup to find the sum of all of the items below. The structure of the list is

["Name", "Item Name", Item Amount, item Cost]

[['Emerie', 'keyboard', '29', '199'], ['Bodie', 'keyboard', '9', '199'], ['Emerie', 'bed', '1', '199'], ['Brecken', 'smartwatch', '9', '199'], ['Brecken', 'SSD', '9', '199']]

How can I get my output to look like this:

[['Emerie', 'keyboard', 29, 199], ['Bodie', 'keyboard', 9, 199], ['Emerie', 'bed', 1, 199], ['Brecken', 'smartwatch', 9, 199], ['Brecken', 'SSD', 9, 199]]

So The strings are strings and the ints are ints

This list is a dynamic list that is subject to change.

I tried many methods but none seem to work

CodePudding user response:

List comphrehension

a = [['Emerie', 'keyboard', '29', '199'], ['Bodie', 'keyboard', '9', '199'], ['Emerie', 'bed', '1', '199'], ['Brecken', 'smartwatch', '9', '199'], ['Brecken', 'SSD', '9', '199']]
[[int(j) if j.decimal() else j for j in i ] for i in a]

output

[['Emerie', 'keyboard', 29, 199],
 ['Bodie', 'keyboard', 9, 199],
 ['Emerie', 'bed', 1, 199],
 ['Brecken', 'smartwatch', 9, 199],
 ['Brecken', 'SSD', 9, 199]]

CodePudding user response:

You can use list comprehension,

In [1]: [[int(j) if j.isdigit() else j for j in i] for i in l]
Out[1]: 
[['Emerie', 'keyboard', 29, 199],
 ['Bodie', 'keyboard', 9, 199],
 ['Emerie', 'bed', 1, 199],
 ['Brecken', 'smartwatch', 9, 199],
 ['Brecken', 'SSD', 9, 199]]
  • Related