gpt4 book ai didi

How to convert string representation of list to a list(如何将列表的字符串表示形式转换为列表)

转载 作者:bug小助手 更新时间:2023-10-25 17:28:59 26 4
gpt4 key购买 nike



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?

我知道我可以使用strip()和plit()来删除空格,并检查非字母字符。但代码变得非常笨拙。有没有我不知道的快速功能?


更多回答
优秀答案推荐

>>> 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:

Ast.wen al_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.




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.

只要有一个字符串化的词典列表,json模块就是一个更好的解决方案。可以使用json.Loads(YOUR_DATA)函数将其转换为列表。


>>> 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'}]


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

评估是危险的--您不应该执行用户输入。



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

如果您的版本是2.6或更高版本,请使用ast而不是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:

如果您使用的是较旧版本的Python,则使用一个简单的正则表达式就可以非常接近您想要的结果:



>>> 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.

这不如上一个解决方案好,例如,它不能正确处理字符串中的转义引号。但它很简单,不涉及危险的求值,如果您使用的是没有AST的较旧的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):

受上面一些适用于基本Python包的答案的启发,我比较了几个包(使用Python3.7.3)的性能:


Method 1: ast

方法一: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

方法二: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.

我很失望地发现,我认为可读性最差的方法是性能最好的方法……在选择最具可读性的选项时,需要考虑一些权衡因素。对于我使用Python的工作负载类型,我通常更看重可读性,而不是性能稍高的选项,但像往常一样,这取决于。



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"]')]


import ast
l = ast.literal_eval('[ "A","B","C" , " D"]')
l = [i.strip() for i in l]


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']


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):

如果你有嵌套列表,它确实会变得有点烦人。不使用正则表达式(这会简化替换),假设你想返回一个扁平的列表(Python的禅宗说扁平比嵌套好):


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.

最后一个解决方案适用于以字符串形式存储的任何列表,无论是否嵌套。



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.

尽管这不是一种安全的方法,但最好的答案是公认的。当答案被发布时,我并没有意识到年龄的危险。



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.

假设您的所有输入都是列表,并且输入中的双引号实际上并不重要,这可以通过一个简单的regexp替换来完成。它有点像Perl-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']

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.

JUNKS变量包含我们不需要的所有字符的已编译regexp(表示速度),使用]作为字符需要一些反斜杠技巧。Re.sub键将所有这些字符替换为空,并在逗号处拆分生成的字符串。


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.

注意,这也删除了条目u‘[“oh no”]’->[u‘ohno’]中的空格。如果这不是您想要的,那么regexp需要稍微改进一下。



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).

如果您知道您的列表只包含带引号的字符串,则此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']

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.

如果您的列表可以有更多的数据类型,甚至在列表中包含列表,那么您将需要一个更完整的语法--就像pyparsing Examples目录中的语法一样,它将处理元组、列表、整数、浮点数和带引号的字符串。



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

在处理存储为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.




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

当您将存储为字符串的列表加载到CSV时,通常会发生这种情况


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

如果您的列表以CSV格式存储,如OP询问:


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

ListItems现在是List



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

为了使用JSON进一步完善Ryan的答案,这个答案中有一个非常方便的转换Unicode的函数。


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']


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

Json包中的json.ads()和json.ump ps()与JSON.parse()和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"]'



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

我想提供一个更直观的模式解决方案与正则表达式。Below函数将包含任意字符串的字符串化列表作为输入。



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).

分步说明:删除所有空格、括号和VALUE_SESPAING(假设它们不是您想要提取的值的一部分,否则会使正则表达式更加复杂)。然后,将清理后的字符串用单引号或双引号分开,并获取非空值(或奇数索引值,无论您的喜好如何)。



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"]"

测试样本:“'21 ',“foo”' 6','0',“A”]”



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!

所以,最终正则表达式赢了!



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):

只需从列表的字符串表示形式中删除第一个和最后一个字符(请参见下面的第三行),就可以省去.strie()函数:


>>> 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'>


And with pure Python - not importing any libraries:

并且使用纯Python-不导入任何库:


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


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.

这不是你想要的。



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']

更多回答

Per comment below, this is dangerous as it simply runs whatever python is in the string. So if someone puts a call to delete everything in there, it happily will.

根据下面的注释,这是危险的,因为它只是运行字符串中的任何python。因此,如果有人呼吁删除其中的所有内容,它会很高兴地这样做。

@PaulKenjora: You're thinking of eval, not ast.literal_eval.

@PaulKenjora:你想的是val,而不是ast.decal_val。

ast.literal_eval is safer than eval, but it's not actually safe. As recent versions of the docs explain: "Warning It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler." It may, in fact, be possible to run arbitrary code via a careful stack-smashing attack, although as far as I know nobody's build a public proof of concept for that.

Ast.decal_val比val更安全,但它实际上并不安全。正如文档的最新版本所解释的那样:“警告,由于PythonAST编译器中的堆栈深度限制,使用足够大/复杂的字符串可能会使Python解释器崩溃。”事实上,可能会通过仔细的堆栈粉碎攻击来运行任意代码,尽管据我所知,还没有人为此构建公开的概念证明。

Well but what to do if the List does not have quotes? e.g. [4 of B, 1 of G]

但是,如果列表中没有引号,该怎么办?例如[B的4个,G的1个]

@sqp_125, then it's a regular list, and you don't need to parse anything?

@SQP_125,那么它是一个常规列表,您不需要解析任何东西?

This works for ints but not for strings in my case because each string is single quoted not double quoted, sigh.

这对整数有效,但在我的例子中不适用于字符串,因为每个字符串都是单引号而不是双引号,叹息。

As per @PaulKenjora's comment, it works for '["a","b"]' but not for "['a','b']".

根据@PaulKenjora的评论,它适用于‘[“a”,“b”]’,但不适用于“[‘a’,‘b’]”。

In my case I had to replace single quotes with double quotes in initial string to ensure it works .replace('\'', '"') But I was sure that data inside that string didn't contain any crucial single/double quotes in it that would affect the final result.

在我的例子中,我必须将初始字符串中的单引号替换为双引号,以确保其正常工作。替换(‘\’‘,’“‘),但我确信该字符串中的数据不包含任何会影响最终结果的关键单引号/双引号。

If user should only enter list of numeric, I think this is the safest way to go to stop malicious intend user.

如果用户只输入数字列表,我认为这是阻止恶意用户最安全的方法。

The ast.literal_eval approach is more general. For example, JSON cannot handle b prefixes for strings, as it does not recognize a separate bytes type. JSON also requires double quotes for the strings.

Ast.decal_eval方法更通用。例如,JSON不能处理字符串的b前缀,因为它不识别单独的字节类型。JSON还要求字符串使用双引号。

Could you please tell me what why did you say “The eval is dangerous - you shouldn’t execute user input.”? I am using 3.6

你能告诉我为什么你说“评估是危险的--你不应该执行用户输入”吗?我用的是3.6

@AaryanDewan if you use eval directly, it will evaluate any valid python expression, which is potentially dangerous. literal_eval solves this problem by only evaluating Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

@AaryanDewan如果您直接使用eval,它将计算任何有效的python表达式,这是潜在的危险。通过只计算Python文字结构:字符串、数字、元组、列表、词典、布尔值和NONE来解决这个问题。

is there any particular reason for there being a u in front of '[ "A","B","C" , " D"]'

‘[“A”,“B”,“C”,“D”]前面有u有什么特殊的原因吗?

The manual method is simply not as powerful, and does less work, so it's not surprising that it's faster. It will not handle escape sequences in the strings, or a different quote type. (The JSON method demands double-quotes, but does process escape sequences.) It also will only process a flat list of strings; the other approaches can handle complex nested data structures.

手动方法没有那么强大,而且工作更少,所以它更快也就不足为奇了。它不会处理字符串中的转义序列或不同的引号类型。(JSON方法需要双引号,但会处理转义序列。)它还将只处理字符串的平面列表;其他方法可以处理复杂的嵌套数据结构。

this would still preserve the spaces inside the quotes

这仍将保留引号内的空格

This is an open invitation to arbitrary code execution, NEVER do this or anything like it unless you know with absolute certainty that the input will always be 100% trusted.

这是对任意代码执行的公开邀请,除非您绝对确定输入始终是100%可信的,否则不要这样做或做任何类似的事情。

I could use this suggestion because I knew my data was always gonna be in that format and was a data processing work.

我可以使用这个建议,因为我知道我的数据总是以这种格式存在,并且是一项数据处理工作。

Cautionary note: this could potentially be dangerous if any of the strings inside list has a comma in between.

警告:如果列表中的任何字符串之间有逗号,这可能是潜在的危险。

This will not work if your string list is a list of lists

如果您的字符串列表是列表列表,则这将不起作用

Notice the method doesn't play well with empty lists. You take '[]' and get back ['']. This might be an issue if you're parsing a column in a data frame. Nice solution otherwise!

请注意,该方法在处理空列表时效果不佳。你拿着‘[]’,然后回到[‘’]。如果您正在解析数据框中的列,这可能是一个问题。除此之外,这是个不错的解决方案!

the list comprehension seems to bee slower than the x.strip('[]').replace('"', '').split(',') solution. Probably because the strip operation is repeated len(x) times instead of 1 and two list are created instead of 1 (the one returned by the 'split()`and the one returned by the comprehension).

列表理解似乎比x.strie(‘[]’).Replace(‘“’,‘).Split(’,‘)解决方案慢。可能是因为剥离操作重复了len(X)次而不是1次,并且创建了两个列表而不是1(由’Split()`返回的列表和由理解返回的列表)。

eval is not recommended in several places on this thread as it will simple run as code whatever is entered, presenting a security risk. it is also a duplicate answer.

不建议在此线程的多个位置运行Eval,因为无论输入什么,它都将简单地作为代码运行,这会带来安全风险。这也是一个重复的答案。

Not sure how this is related to the question... list(reader) gives a list of lists. Each inner list is a list of strings of the csv columns. There is no string representation of a list there to begin with...

我不知道这和问题有什么关系... list(reader)给出列表的列表。每个内部列表都是csv列的字符串列表。这里没有一个列表的字符串表示.

@Tomerikoo string representation of list is exactly the same only it's in the file.

@Tmerikoo字符串表示List完全相同,只是它在文件中。

No. A string representation of a list is "['1', '2', '3']". When you read a csv file with csv.reader, each line is ['1', '2', '3']. That is a list of strings. Not a string representation of a list...

不可以。列表的字符串表示是“'1 ',' 2','3']"。当你用csv.reader读取一个csv文件时,每一行都是“1”,“2”,“3”]。这是一个字符串列表。不是列表的字符串表示.

@Tomerikoo how about you store list in file and than use any method here to restore it.

@Tmerikoo您可以将列表存储在文件中,然后使用此处的任何方法来恢复它。

Ok, let's say the csv has literally [1, 2, 3] inside it. Let's say a csv row is [1,2,3] 4 5. Reading it with list(reader) will give [["[1,2,3]", "4", "5"], ...] then doing rows[0] will give ["[1,2,3]", "4", "5"]. Again, I don't see how that answers the question...

好的,假设CSV里面有字面意义上的[1,2,3]。假设CSV行是[1,2,3]4 5。使用List(Reader)读取它将得到[[“[1,2,3],”4“,”5“],...]然后执行行[0]将得到[“[1,2,3]”,“4”,“5”]。再说一次,我不明白这怎么能回答这个问题。

The only new information here is a further processing step that is unrelated to the question that was asked, and also somewhere between irrelevant and harmful in most cases. The data generally should be understood as strings (unicode objects in 2.x), not byte sequences.

这里唯一的新信息是与所提出的问题无关的进一步处理步骤,而且在大多数情况下也介于无关和有害之间。数据通常应该理解为字符串(2.x中的Unicode对象),而不是字节序列。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com