如何将2D列表从字符串转换为Python列表?

发布于 2025-01-20 13:34:03 字数 562 浏览 0 评论 0原文

我有一个字符串,是一个2D数组,带有以下字段[FruitName,Qty,Date,Time]

示例列表:

['Apples',1,'04 -07-2022','16:35' ],['Oranges',5,'04 -07-2022','18:35'],['Mangoes',10,'04 -07-2022','16:00']

i想要将上述内容存储在Python(FruitsPurchaseSt)的列表中,并访问它。

例如,如果我想购买购买的芒果数量,我会通过以下内容进行访问:

mangoqty = fruitspurchaselist [2] [1] [1]

编辑:

列表也有一些空白。

示例列表:

['Apples',1,'04 -07-2022','16:35'],['Oranges',5,'04 -07-2022','18:35'], ['Mangoes',10,'04 -07-2022','16:00'],['Bananas','04-09-2022','11:00']

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]

EDIT:

The list also has some blanks.

Sample list:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

第几種人 2025-01-27 13:34:03

编辑:原始版本使用eval;新版本使用标准 ast 模块中的 literal_eval

如果您有一个表示列表列表的字符串并希望将其转换为列表,

  1. 可以使用内置的 Python 函数 eval()< /代码>
    文档)。 eval() 接受一个字符串作为参数,并且
    将其计算为 Python 表达式(解析字符串后)。这
    返回计算表达式的结果。如果您确实使用 eval,则必须确保 eval 的输入源可信
  2. 应该(请参阅帖子末尾的讨论)使用函数literal_eval文档)来自 Python 标准库的 ast 模块。

此代码使用 literal_eval 执行您想要的操作(eval 实现相同的效果,但请参阅下面的注释)。

from pprint import pprint
from ast import literal_eval
# import re 

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

s = s.replace(",,", ",'',")
# s = re.sub(r', *,', ",'',", s) 

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

上面将所有出现的 ',,' 替换为 ",'',"。如果在空字段中逗号之间有任意数量的空格(但没有其他空格),请删除 s.replace 行并取消注释两个注释掉的行。使用 re.sub 是一种更通用的解决方案。

输出

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

Mango Quantity: 10

安全说明


在许多情况下,evalliteral_eval 将实现相同的效果,如本例所示。然而,众所周知,eval 可能非常危险。 eval 获取其字符串参数,对其进行解析并将其计算为 Python 表达式。这可以是任意 Python 表达式。一个问题是Python 允许用户访问和删除系统文件(例如通过os 模块)。因此,不良行为者可能会提供您输入到 eval 中的危险数据,这可能会损坏您的系统。这就是为什么在将输入源提供给 eval 之前,您需要格外小心,确保您可以信任输入源literal_eval 也接受字符串作为参数,但这仅限于包含(引用上面引用的 literal_eval 文档)

Python 文字结构:字符串、字节、数字、元组、列表、字典、集合、布尔值、None 和省略号。这可用于安全地评估包含来自不受信任来源的 Python 值的字符串,而无需自己解析这些值。它无法计算任意复杂的表达式[.]

在您的情况下,您知道您的字符串数据表示一个嵌套列表,该列表应该只包含数字和字符串作为元素。因此为了安全起见,请使用literal_eval,它不会计算不允许的表达式。因此,如果您的列表中包含通常会评估为危险内容的元素(eval 会评估),literal_eval 不会评估它 - 它仅限于 Python 文字结构。在这种情况下,即使您知道并且绝对信任您的输入源,使用 literal_eval 也没有什么坏处。

注意安全!

希望这有帮助。如果有任何问题/疑虑,请告诉我!

EDIT: original version used eval; new version uses literal_eval from the standard ast module.

If you have a string that represents a list of lists and want to turn that into a list,

  1. 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. If you do use eval, you must be sure that the input source to eval is trusted.
  2. you should (see discussion at end of post) use the function literal_eval (documentation) from the ast module from the Python Standard Library.

This code does what you want using literal_eval (eval achieves the same effect but see note below).

from pprint import pprint
from ast import literal_eval
# import re 

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

s = s.replace(",,", ",'',")
# s = re.sub(r', *,', ",'',", s) 

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

The above replaces all occurrences of ',,' with ",'',". If in the empty fields there are an arbitrary number of spaces between the commas (but nothing else), remove the s.replace line and uncomment the two commented-out lines. Using re.sub is a more general solution.

Output

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

Mango Quantity: 10

Safety Note


In many contexts, eval and literal_eval will achieve the same effect, as in this example. However, eval is known to be potentially very dangerous. eval takes its string argument, parses it and evaluates it as a Python expression. This can be an arbitrary Python expression. One concern is that Python permits users to access and delete system files (e.g. via the os module). So a bad-actor may supply dangerous data that you feed into eval, which could corrupt your system. This is why you need to be extra careful that you can trust the input source before supplying it to eval. literal_eval also accepts a string as an argument, but this is restricted to only contain (quote from literal_eval doc cited above)

Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis. This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions[.]

In your case, you know that your string data represents a nested list that should only have numbers and strings as elements. So to be safe, use literal_eval, which would not evaluate a non-allowed expression. So if your list had elements that would normally evaluate to something dangerous (which eval would evaluate), literal_eval would not evaluate it -- it is restricted to Python literal structures. In this case, even if you know and absolutely trust your input source, there is no harm in using literal_eval instead.

Be safe!

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

热情消退 2025-01-27 13:34:03

您可以使用 append()其他列表!使用for循环循环浏览每个字符串元素,并将其附加到您的新列表中。访问示例中显示的元素-gode> listName [整个列表中的元素索引] [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}")

输出如下:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文