如何将列表的字符串表示形式转换为列表

发布于 2025-02-04 09:15:45 字数 306 浏览 3 评论 0原文

我想知道,最简单的方法是将以下列表的字符串表示形式转换为list

x = '[ "A","B","C" , " D"]'

即使在用户将空间放在逗号之间以及引号内的空格之间的情况下,我也需要处理它并将其转换为:

x = ["A", "B", "C", "D"] 

我知道我可以用strip()split()剥离空格,并检查非字母字符。但是代码变得非常笨拙。我不知道有一个快速功能吗?

I was wondering what the simplest way is to convert a string representation of a list like the following to a list:

x = '[ "A","B","C" , " D"]'

Even in cases where the user puts spaces in between the commas, and spaces inside of the quotes, I need to handle that as well and convert it to:

x = ["A", "B", "C", "D"] 

I know I can strip spaces with strip() and split() and check for non-letter characters. But the code was getting very kludgy. Is there a quick function that I'm not aware of?

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

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

发布评论

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

评论(22

第七度阳光i 2025-02-11 09:15:45
>>> import ast
>>> x = '[ "A","B","C" , " D"]'
>>> x = ast.literal_eval(x)
>>> x
['A', 'B', 'C', ' D']
>>> x = [n.strip() for n in x]
>>> x
['A', 'B', 'C', 'D']

ast.literal_eval

评估仅包含python文字或容器显示的表达节点或字符串。所提供的字符串或节点只能由以下python文字结构组成:字符串,字节,数字,元组,列表,列表,dict,sets,booleans,none and eLLIPSIS 。<<。 /p>

这可用于评估包含python值的字符串,而无需自行解析值。它无法评估任意复杂的表达式,例如涉及操作员或索引。

>>> import ast
>>> x = '[ "A","B","C" , " D"]'
>>> x = ast.literal_eval(x)
>>> x
['A', 'B', 'C', ' D']
>>> x = [n.strip() for n in x]
>>> x
['A', 'B', 'C', 'D']

ast.literal_eval:

Evaluate an expression node or a string containing only a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis.

This can be used for evaluating strings containing Python values without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

濫情▎り 2025-02-11 09:15:45

JSON 当有一个更好的解决方案时A 弦乐字典列表。 json.loads(your_data)函数可用于将其转换为列表。

>>> import json
>>> x = '[ "A","B","C" , " D"]'
>>> json.loads(x)
['A', 'B', 'C', ' D']

相似地

>>> x = '[ "A","B","C" , {"D":"E"}]'
>>> json.loads(x)
['A', 'B', 'C', {'D': 'E'}]

The json module is a better solution whenever there is a stringified list of dictionaries. The json.loads(your_data) function can be used to convert it to a list.

>>> import json
>>> x = '[ "A","B","C" , " D"]'
>>> json.loads(x)
['A', 'B', 'C', ' D']

Similarly

>>> x = '[ "A","B","C" , {"D":"E"}]'
>>> json.loads(x)
['A', 'B', 'C', {'D': 'E'}]
隔纱相望 2025-02-11 09:15:45

eval是危险的 - 您不应执行用户输入。

如果您有2.6或更新,请使用AST而不是eval:

>>> import ast
>>> ast.literal_eval('["A","B" ,"C" ," D"]')
["A", "B", "C", " D"]

一旦拥有,strip字符串。

如果您使用的是较旧版本的Python,则可以通过简单的正则表达式非常接近您想要的内容:

>>> x='[  "A",  " B", "C","D "]'
>>> re.findall(r'"\s*([^"]*?)\s*"', x)
['A', 'B', 'C', 'D']

它不如AST解决方案,例如,它无法正确处理字符串中的逃脱引号。但这很简单,不涉及危险的评估,如果您在没有AST的较旧的python上,则可能足以满足您的目的。

The eval is dangerous - you shouldn't execute user input.

If you have 2.6 or newer, use ast instead of eval:

>>> import ast
>>> ast.literal_eval('["A","B" ,"C" ," D"]')
["A", "B", "C", " D"]

Once you have that, strip the strings.

If you're on an older version of Python, you can get very close to what you want with a simple regular expression:

>>> x='[  "A",  " B", "C","D "]'
>>> re.findall(r'"\s*([^"]*?)\s*"', x)
['A', 'B', 'C', 'D']

This isn't as good as the ast solution, for example it doesn't correctly handle escaped quotes in strings. But it's simple, doesn't involve a dangerous eval, and might be good enough for your purpose if you're on an older Python without ast.

梦明 2025-02-11 09:15:45

有一个快速的解决方案:

x = eval('[ "A","B","C" , " D"]')

列表元素中有害的白空间可以以这种方式删除:

x = [x.strip() for x in eval('[ "A","B","C" , " D"]')]

There is a quick solution:

x = eval('[ "A","B","C" , " D"]')

Unwanted whitespaces in the list elements may be removed in this way:

x = [x.strip() for x in eval('[ "A","B","C" , " D"]')]
囚我心虐我身 2025-02-11 09:15:45

从上面的一些答案中启发了与基本Python软件包一起使用的答案,我比较了少数的性能(使用Python 3.7.3):

方法1:AST

import ast

list(map(str.strip, ast.literal_eval(u'[ "A","B","C" , " D"]')))
# ['A', 'B', 'C', 'D']

import timeit
timeit.timeit(stmt="list(map(str.strip, ast.literal_eval(u'[ \"A\",\"B\",\"C\" , \" D\"]')))", setup='import ast', number=100000)
# 1.292875313000195

方法2:JSON

import json
list(map(str.strip, json.loads(u'[ "A","B","C" , " D"]')))
# ['A', 'B', 'C', 'D']

import timeit
timeit.timeit(stmt="list(map(str.strip, json.loads(u'[ \"A\",\"B\",\"C\" , \" D\"]')))", setup='import json', number=100000)
# 0.27833264000014424

方法3:没有进口

list(map(str.strip, u'[ "A","B","C" , " D"]'.strip('][').replace('"', '').split(',')))
# ['A', 'B', 'C', 'D']

import timeit
timeit.timeit(stmt="list(map(str.strip, u'[ \"A\",\"B\",\"C\" , \" D\"]'.strip('][').replace('\"', '').split(',')))", number=100000)
# 0.12935059100027502

我很失望地看到我认为最糟糕的可读性的方法是具有最佳性能的方法...在使用最可读的选项时,有权衡需要考虑...对于工作负载的类型,我通常使用Python,因为我通常将可读性评估为性能稍高的选项,但是像往常一样,它取决于。

Inspired from some of the answers above that work with base Python packages I compared the performance of a few (using Python 3.7.3):

Method 1: ast

import ast

list(map(str.strip, ast.literal_eval(u'[ "A","B","C" , " D"]')))
# ['A', 'B', 'C', 'D']

import timeit
timeit.timeit(stmt="list(map(str.strip, ast.literal_eval(u'[ \"A\",\"B\",\"C\" , \" D\"]')))", setup='import ast', number=100000)
# 1.292875313000195

Method 2: json

import json
list(map(str.strip, json.loads(u'[ "A","B","C" , " D"]')))
# ['A', 'B', 'C', 'D']

import timeit
timeit.timeit(stmt="list(map(str.strip, json.loads(u'[ \"A\",\"B\",\"C\" , \" D\"]')))", setup='import json', number=100000)
# 0.27833264000014424

Method 3: no import

list(map(str.strip, u'[ "A","B","C" , " D"]'.strip('][').replace('"', '').split(',')))
# ['A', 'B', 'C', 'D']

import timeit
timeit.timeit(stmt="list(map(str.strip, u'[ \"A\",\"B\",\"C\" , \" D\"]'.strip('][').replace('\"', '').split(',')))", number=100000)
# 0.12935059100027502

I was disappointed to see what I considered the method with the worst readability was the method with the best performance... there are trade-offs to consider when going with the most readable option... for the type of workloads I use Python for I usually value readability over a slightly more performant option, but as usual it depends.

沉默的熊 2025-02-11 09:15:45
import ast
l = ast.literal_eval('[ "A","B","C" , " D"]')
l = [i.strip() for i in l]
import ast
l = ast.literal_eval('[ "A","B","C" , " D"]')
l = [i.strip() for i in l]
青衫儰鉨ミ守葔 2025-02-11 09:15:45

如果仅是一个维度列表,则可以在不导入任何内容的情况下完成:

>>> x = u'[ "A","B","C" , " D"]'
>>> ls = x.strip('[]').replace('"', '').replace(' ', '').split(',')
>>> ls
['A', 'B', 'C', 'D']

If it's only a one dimensional list, this can be done without importing anything:

>>> x = u'[ "A","B","C" , " D"]'
>>> ls = x.strip('[]').replace('"', '').replace(' ', '').split(',')
>>> ls
['A', 'B', 'C', 'D']
橙幽之幻 2025-02-11 09:15:45

无需导入任何东西或评估。您可以在大多数基本用例中以一行进行此操作,包括原始问题中给出的用例。

一个衬里

l_x = [i.strip() for i in x[1:-1].replace('"',"").split(',')]

说明

x = '[ "A","B","C" , " D"]'
# String indexing to eliminate the brackets.
# Replace, as split will otherwise retain the quotes in the returned list
# Split to convert to a list
l_x = x[1:-1].replace('"',"").split(',')

输出

for i in range(0, len(l_x)):
    print(l_x[i])
# vvvv output vvvvv
'''
 A
B
C
  D
'''
print(type(l_x)) # out: class 'list'
print(len(l_x)) # out: 4

您可以使用列表理解根据需要解析并清理此列表。

l_x = [i.strip() for i in l_x] # list comprehension to clean up
for i in range(0, len(l_x)):
    print(l_x[i])
# vvvvv output vvvvv
'''
A
B
C
D
'''

嵌套列表,

如果您的列表列表,它确实会变得更加烦人。不使用正则施法(可以简化替换),并假设您想返回一个扁平的列表(以及 Zen说平面比嵌套):

x = '[ "A","B","C" , " D", ["E","F","G"]]'
l_x = x[1:-1].split(',')
l_x = [i
    .replace(']', '')
    .replace('[', '')
    .replace('"', '')
    .strip() for i in l_x
]
# returns ['A', 'B', 'C', 'D', 'E', 'F', 'G']

如果您需要保留嵌套列表,则会变得有些丑陋,但是只能使用正则表达式并列表理解:最后一个解决方案将会完成:

import re

x = '[ "A","B","C" , " D", "["E","F","G"]","Z", "Y", "["H","I","J"]", "K", "L"]'
# Clean it up so the regular expression is simpler
x = x.replace('"', '').replace(' ', '')
# Look ahead for the bracketed text that signifies nested list
l_x = re.split(r',(?=\[[A-Za-z0-9\',]+\])|(?<=\]),', x[1:-1])
print(l_x)
# Flatten and split the non nested list items
l_x0 = [item for items in l_x for item in items.split(',') if not '[' in items]
# Convert the nested lists to lists
l_x1 = [
    i[1:-1].split(',') for i in l_x if '[' in i
]
# Add the two lists
l_x = l_x0 + l_x1

这个最后的解决方案将会在存储为字符串的任何列表上工作,无论是否嵌套。

There isn't any need to import anything or to evaluate. You can do this in one line for most basic use cases, including the one given in the original question.

One liner

l_x = [i.strip() for i in x[1:-1].replace('"',"").split(',')]

Explanation

x = '[ "A","B","C" , " D"]'
# String indexing to eliminate the brackets.
# Replace, as split will otherwise retain the quotes in the returned list
# Split to convert to a list
l_x = x[1:-1].replace('"',"").split(',')

Outputs:

for i in range(0, len(l_x)):
    print(l_x[i])
# vvvv output vvvvv
'''
 A
B
C
  D
'''
print(type(l_x)) # out: class 'list'
print(len(l_x)) # out: 4

You can parse and clean up this list as needed using list comprehension.

l_x = [i.strip() for i in l_x] # list comprehension to clean up
for i in range(0, len(l_x)):
    print(l_x[i])
# vvvvv output vvvvv
'''
A
B
C
D
'''

Nested lists

If you have nested lists, it does get a bit more annoying. Without using regex (which would simplify the replace), and assuming you want to return a flattened list (and the zen of python says flat is better than nested):

x = '[ "A","B","C" , " D", ["E","F","G"]]'
l_x = x[1:-1].split(',')
l_x = [i
    .replace(']', '')
    .replace('[', '')
    .replace('"', '')
    .strip() for i in l_x
]
# returns ['A', 'B', 'C', 'D', 'E', 'F', 'G']

If you need to retain the nested list it gets a bit uglier, but it can still be done just with regular expressions and list comprehension:

import re

x = '[ "A","B","C" , " D", "["E","F","G"]","Z", "Y", "["H","I","J"]", "K", "L"]'
# Clean it up so the regular expression is simpler
x = x.replace('"', '').replace(' ', '')
# Look ahead for the bracketed text that signifies nested list
l_x = re.split(r',(?=\[[A-Za-z0-9\',]+\])|(?<=\]),', x[1:-1])
print(l_x)
# Flatten and split the non nested list items
l_x0 = [item for items in l_x for item in items.split(',') if not '[' in items]
# Convert the nested lists to lists
l_x1 = [
    i[1:-1].split(',') for i in l_x if '[' in i
]
# Add the two lists
l_x = l_x0 + l_x1

This last solution will work on any list stored as a string, nested or not.

撕心裂肺的伤痛 2025-02-11 09:15:45

你可以做这个

**

x = '[ "A","B","C" , " D"]'
print(eval(x))

**
最好的一个是公认的答案,

尽管这不是一种安全的方法,但最好的答案是被公认的答案。
回答时,不知道评估危险。

You can do this

**

x = '[ "A","B","C" , " D"]'
print(eval(x))

**
best one is the accepted answer

Though this is not a safe way, the best answer is the accepted one.
wasn't aware of the eval danger when answer was posted.

冷清清 2025-02-11 09:15:45

假设您的所有输入都是列表,并且输入中的双引号实际上无关紧要,则可以通过简单的RegexP替换来完成。有点 perl-y-y ,但它的起作用就像魅力。还请注意,输出现在是Unicode字符串的列表,您没有指定需要它,但是给定Unicode输入,这似乎是有意义的。

import re
x = u'[ "A","B","C" , " D"]'
junkers = re.compile('[[" \]]')
result = junkers.sub('', x).split(',')
print result
--->  [u'A', u'B', u'C', u'D']

Junkers变量包含一个我们不想要的所有字符的编译的REGEXP(用于速度),用作字符需要一些后斜切的欺骗。
re.sub 一无所有地替换所有这些字符,我们在逗号上拆分了结果字符串。

请注意,这还从内部条目中删除了空间, [u'ohno']。如果这不是您想要的,那么Regexp就必须加一点汤。

Assuming that all your inputs are lists and that the double quotes in the input actually don't matter, this can be done with a simple regexp replace. It is a bit perl-y, but it works like a charm. Note also that the output is now a list of Unicode strings, you didn't specify that you needed that, but it seems to make sense given Unicode input.

import re
x = u'[ "A","B","C" , " D"]'
junkers = re.compile('[[" \]]')
result = junkers.sub('', x).split(',')
print result
--->  [u'A', u'B', u'C', u'D']

The junkers variable contains a compiled regexp (for speed) of all characters we don't want, using ] as a character required some backslash trickery.
The re.sub replaces all these characters with nothing, and we split the resulting string at the commas.

Note that this also removes spaces from inside entries u'["oh no"]' ---> [u'ohno']. If this is not what you wanted, the regexp needs to be souped up a bit.

后eg是否自 2025-02-11 09:15:45

如果您知道您的列表仅包含引用的字符串,则此pyparsing示例将为您提供剥离字符串列表(甚至保留原始的Unicode-ness)。

>>> from pyparsing import *
>>> x =u'[ "A","B","C" , " D"]'
>>> LBR,RBR = map(Suppress,"[]")
>>> qs = quotedString.setParseAction(removeQuotes, lambda t: t[0].strip())
>>> qsList = LBR + delimitedList(qs) + RBR
>>> print qsList.parseString(x).asList()
[u'A', u'B', u'C', u'D']

如果您的列表可以具有更多的数据类型,甚至可以包含列表中的列表,那么您将需要更完整的语法 - 例如这个在pyparsing示例中,该目录将处理元组,列表,ints,floats和rowing struged strings。

If you know that your lists only contain quoted strings, this pyparsing example will give you your list of stripped strings (even preserving the original Unicode-ness).

>>> from pyparsing import *
>>> x =u'[ "A","B","C" , " D"]'
>>> LBR,RBR = map(Suppress,"[]")
>>> qs = quotedString.setParseAction(removeQuotes, lambda t: t[0].strip())
>>> qsList = LBR + delimitedList(qs) + RBR
>>> print qsList.parseString(x).asList()
[u'A', u'B', u'C', u'D']

If your lists can have more datatypes, or even contain lists within lists, then you will need a more complete grammar - like this one in the pyparsing examples directory, which will handle tuples, lists, ints, floats, and quoted strings.

暖心男生 2025-02-11 09:15:45

您可能会遇到此类问题,同时处理存储为Pandas DataFrame的刮擦数据。

如果值列表以文本为单位,则该解决方案就像魅力一样。

def textToList(hashtags):
    return hashtags.strip('[]').replace('\'', '').replace(' ', '').split(',')

hashtags = "[ 'A','B','C' , ' D']"
hashtags = textToList(hashtags)

Output: ['A', 'B', 'C', 'D']

无需外部库。

You may run into such problem while dealing with scraped data stored as Pandas DataFrame.

This solution works like charm if the list of values is present as text.

def textToList(hashtags):
    return hashtags.strip('[]').replace('\'', '').replace(' ', '').split(',')

hashtags = "[ 'A','B','C' , ' D']"
hashtags = textToList(hashtags)

Output: ['A', 'B', 'C', 'D']

No external library required.

笨死的猪 2025-02-11 09:15:45

形式时,通常会发生这种情况

通常会在将字符串存储到CSV 的列表中以op问:

x = '[ "A","B","C" , " D"]'

这是如何将其加载回列表的

import csv
with open('YourCSVFile.csv') as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    rows = list(reader)

listItems = rows[0]

ListItems 现在列表

This usually happens when you load list stored as string to CSV

If you have your list stored in CSV in form like OP asked:

x = '[ "A","B","C" , " D"]'

Here is how you can load it back to list:

import csv
with open('YourCSVFile.csv') as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    rows = list(reader)

listItems = rows[0]

listItems is now list

离笑几人歌 2025-02-11 09:15:45

要进一步完成使用JSON,一个非常方便的转换Unicode的功能在此答案

带有双引号或单个引号的示例:

>print byteify(json.loads(u'[ "A","B","C" , " D"]')
>print byteify(json.loads(u"[ 'A','B','C' , ' D']".replace('\'','"')))
['A', 'B', 'C', ' D']
['A', 'B', 'C', ' D']

To further complete Ryan's answer using JSON, one very convenient function to convert Unicode is in this answer.

Example with double or single quotes:

>print byteify(json.loads(u'[ "A","B","C" , " D"]')
>print byteify(json.loads(u"[ 'A','B','C' , ' D']".replace('\'','"')))
['A', 'B', 'C', ' D']
['A', 'B', 'C', ' D']
白龙吟 2025-02-11 09:15:45

JSON.LOADS()JSON.DUMPS()来自JSON软件包是JavaScript JSON.PARSE() and code>和的等效方式json.stringify(),请使用JSON解决方案保持生活更简单

import json
a = '[ "A","B","C" , " D"]'
print(json.loads(a)) #['A', 'B', 'C', ' D']
b = ['A', 'B', 'C', ' D']
print(json.dumps(b)) # '["A", "B", "C", " D"]'

json.loads() and json.dumps() from json package is the equivalent way of javascript JSON.parse() and JSON.stringify() so use json solution to keep life simpler

import json
a = '[ "A","B","C" , " D"]'
print(json.loads(a)) #['A', 'B', 'C', ' D']
b = ['A', 'B', 'C', ' D']
print(json.dumps(b)) # '["A", "B", "C", " D"]'

星星的轨迹 2025-02-11 09:15:45

我想通过Regex提供更直观的图案解决方案。
以下函数将输入作为包含任意字符串的弦乐列表。

逐步说明:
您可以删除所有围墙,括号和value_separator(前提是它们不是要提取的值的一部分,否则使得正则更复杂)。然后,您将清洁的字符串拆分在单引号或双引号上,并以非空值(或偏好,无论是奇数索引值)。

def parse_strlist(sl):
import re
clean = re.sub("[\[\],\s]","",sl)
splitted = re.split("[\'\"]",clean)
values_only = [s for s in splitted if s != '']
return values_only

testSample :“ ['21',“ foo”'6','0',“ a”]”

I would like to provide a more intuitive patterning solution with regex.
The below function takes as input a stringified list containing arbitrary strings.

Stepwise explanation:
You remove all whitespacing,bracketing and value_separators (provided they are not part of the values you want to extract, else make the regex more complex). Then you split the cleaned string on single or double quotes and take the non-empty values (or odd indexed values, whatever the preference).

def parse_strlist(sl):
import re
clean = re.sub("[\[\],\s]","",sl)
splitted = re.split("[\'\"]",clean)
values_only = [s for s in splitted if s != '']
return values_only

testsample: "['21',"foo" '6', '0', " A"]"

醉殇 2025-02-11 09:15:45

因此,遵循所有答案,我决定为最常见的方法计时:

from time import time
import re
import json

my_str = str(list(range(19)))
print(my_str)

reps = 100000

start = time()
for i in range(0, reps):
    re.findall("\w+", my_str)
print("Regex method:\t", (time() - start) / reps)

start = time()
for i in range(0, reps):
    json.loads(my_str)
print("JSON method:\t", (time() - start) / reps)

start = time()
for i in range(0, reps):
    ast.literal_eval(my_str)
print("AST method:\t\t", (time() - start) / reps)

start = time()
for i in range(0, reps):
    [n.strip() for n in my_str]
print("strip method:\t", (time() - start) / reps)

    regex method:     6.391477584838867e-07
    json method:     2.535374164581299e-06
    ast method:         2.4425282478332518e-05
    strip method:     4.983267784118653e-06

最终胜利!

So, following all the answers I decided to time the most common methods:

from time import time
import re
import json

my_str = str(list(range(19)))
print(my_str)

reps = 100000

start = time()
for i in range(0, reps):
    re.findall("\w+", my_str)
print("Regex method:\t", (time() - start) / reps)

start = time()
for i in range(0, reps):
    json.loads(my_str)
print("JSON method:\t", (time() - start) / reps)

start = time()
for i in range(0, reps):
    ast.literal_eval(my_str)
print("AST method:\t\t", (time() - start) / reps)

start = time()
for i in range(0, reps):
    [n.strip() for n in my_str]
print("strip method:\t", (time() - start) / reps)

    regex method:     6.391477584838867e-07
    json method:     2.535374164581299e-06
    ast method:         2.4425282478332518e-05
    strip method:     4.983267784118653e-06

So in the end regex wins!

瞳孔里扚悲伤 2025-02-11 09:15:45

您可以通过切片列表的字符串表示形式中的第一个和最后一个字符来保存.strip()函数(请参见下面的第三行):

>>> mylist=[1,2,3,4,5,'baloney','alfalfa']
>>> strlist=str(mylist)
['1', ' 2', ' 3', ' 4', ' 5', " 'baloney'", " 'alfalfa'"]
>>> mylistfromstring=(strlist[1:-1].split(', '))
>>> mylistfromstring[3]
'4'
>>> for entry in mylistfromstring:
...     print(entry)
...     type(entry)
...
1
<class 'str'>
2
<class 'str'>
3
<class 'str'>
4
<class 'str'>
5
<class 'str'>
'baloney'
<class 'str'>
'alfalfa'
<class 'str'>

You can save yourself the .strip() function by just slicing off the first and last characters from the string representation of the list (see the third line below):

>>> mylist=[1,2,3,4,5,'baloney','alfalfa']
>>> strlist=str(mylist)
['1', ' 2', ' 3', ' 4', ' 5', " 'baloney'", " 'alfalfa'"]
>>> mylistfromstring=(strlist[1:-1].split(', '))
>>> mylistfromstring[3]
'4'
>>> for entry in mylistfromstring:
...     print(entry)
...     type(entry)
...
1
<class 'str'>
2
<class 'str'>
3
<class 'str'>
4
<class 'str'>
5
<class 'str'>
'baloney'
<class 'str'>
'alfalfa'
<class 'str'>
冰雪之触 2025-02-11 09:15:45

并使用纯python-没有导入任何库:

[x for x in  x.split('[')[1].split(']')[0].split('"')[1:-1] if x not in[',',' , ',', ']]

And with pure Python - not importing any libraries:

[x for x in  x.split('[')[1].split(']')[0].split('"')[1:-1] if x not in[',',' , ',', ']]
动次打次papapa 2025-02-11 09:15:45

如果您不想导入任何库:

x = '[ "A","B","C" , " D"]'
def toList(stringList):
  stringList = stringList.split('[')[1]# removes "["
  stringList = stringList.split(']')[0]# removes "]"
  stringList = stringList.split(',')#gets objects in the list
  return [text.strip()[1:-1] for text in stringList] #eliminate additional " or ' in the string.
toList(x)

输出:

['A', 'B', 'C', ' D']

解决方案是不起作用

x = '[ "A","B,F","C" , " D"]'

此方法的警告是,如果您的字符串内有逗号,则该

['A', '', '', 'C', ' D']

的你想要。

This is another solution if you don't want to import any library:

x = '[ "A","B","C" , " D"]'
def toList(stringList):
  stringList = stringList.split('[')[1]# removes "["
  stringList = stringList.split(']')[0]# removes "]"
  stringList = stringList.split(',')#gets objects in the list
  return [text.strip()[1:-1] for text in stringList] #eliminate additional " or ' in the string.
toList(x)

Output:

['A', 'B', 'C', ' D']

The caveat to this method is that it doesn't work if you have comma inside your string for example if your input is

x = '[ "A","B,F","C" , " D"]'

your output will be

['A', '', '', 'C', ' D']

which is not what you want.

沙与沫 2025-02-11 09:15:45

这是一个函数的实现,将字符串转换为并不是很短的列表,但它非常简单明了,可以按照手动执行此操作,可以做您期望的事情以及您将要做的事情:

def string_to_list(value):
    assert(isinstance(value, (str, list)))
    if isinstance(value, list):
        return value
    assert(value.startswith("[") and value.endswith("]"))
    value = value.strip().removeprefix("[").removesuffix("]").split(",")
    for i, item in enumerate(value):
        item = item.strip()
        if item.startswith("'") and item.endswith("'"):
            item = item.removeprefix("'").removesuffix("'")
        elif item.startswith('"') and item.endswith('"'):
            item = item.removeprefix('"').removesuffix('"')
        value[i] = item
    return value

Here is an implementation of a function to convert a string to a list that isn't very short, but it is very simple and straightforward and does exactly what you would expect it to and what you would do if you were doing this manually:

def string_to_list(value):
    assert(isinstance(value, (str, list)))
    if isinstance(value, list):
        return value
    assert(value.startswith("[") and value.endswith("]"))
    value = value.strip().removeprefix("[").removesuffix("]").split(",")
    for i, item in enumerate(value):
        item = item.strip()
        if item.startswith("'") and item.endswith("'"):
            item = item.removeprefix("'").removesuffix("'")
        elif item.startswith('"') and item.endswith('"'):
            item = item.removeprefix('"').removesuffix('"')
        value[i] = item
    return value
朕就是辣么酷 2025-02-11 09:15:45

该解决方案比我在以前的答案中阅读的某些内容要简单,但是它需要匹配列表的所有功能。

x = '[ "A","B","C" , " D"]'
[i.strip() for i in x.split('"') if len(i.strip().strip(',').strip(']').strip('['))>0]

输出:

['A', 'B', 'C', 'D']

This solution is simpler than some I read in the previous answers, but it requires to match all features of the list.

x = '[ "A","B","C" , " D"]'
[i.strip() for i in x.split('"') if len(i.strip().strip(',').strip(']').strip('['))>0]

Output:

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