Home > Enterprise >  How can I convert a 2d list from string into a python list?
How can I convert a 2d list from string into a python list?

Time:04-12

I have a string, which is a 2d array, with the following fields [fruitname,qty,date,time]

Sample list:

['apples',1,'04-07-2022','16:35'],['oranges',5,'04-07-2022','18:35'],['mangoes',10,'04-07-2022','16:00']

I would like to store the above in a list in python (fruitsPurchaseList) and access it.

For example, if I wanted to get the quantity of mangoes purchased, I'd access it by something like:

mangoQty = fruitsPurchaseList[2][1]

CodePudding user response:

You can use append() to add any element to a list in python - this includes other lists! Use a for loop to loop through each string element and append it to your new list. Access the elements as you showed in your example - listname[element index in whole list][element index in sublist].

string = ['apples',1,'04-07-2022','16:35'],['oranges',5,'04-07-2022','18:35'],['mangoes',10,'04-07-2022','16:00']
fruitsPurchaseList = []

for s in string:
    fruitsPurchaseList.append(s)

print(f"The fruits purchase list is: ${fruitsPurchaseList}")

mangoQty = fruitsPurchaseList[2][1]

print(f"The mango quantity is: ${mangoQty}")

Output is as follows:

The fruits purchase list is: $[['apples', 1, '04-07-2022', '16:35'], ['oranges', 5, '04-07-2022', '18:35'], ['mangoes', 10, '04-07-2022', '16:00']]
The mango quantity is: $10

CodePudding user response:

If you have a string that represents a list of lists and want to turn that into a list, you can use the built-in Python function eval() (documentation). eval() accepts a string as an argument and evaluates it as a Python expression (after parsing the string). The result of the evaluated expression is returned. For example,

from pprint import pprint 

s = """
[
['apples', 1, '04-07-2022', '16:35'],
['oranges', 5, '04-07-2022', '18:35'],
['mangoes', 10, '04-07-2022', '16:00']
]
"""

l = eval(s)
pprint(l)
print(f"\nMango Quantity: {l[2][1]}")

Output

[['apples', 1, '04-07-2022', '16:35'],
 ['oranges', 5, '04-07-2022', '18:35'],
 ['mangoes', 10, '04-07-2022', '16:00']]

Mango Quantity: 10

Hope this helps. Please let me know if there are questions/concerns!

  • Related