简体   繁体   English

字符串到列表的转换

[英]Conversion of Strings to list

Can someone please help me with a simple code that returns a list as an output to list converted to string? 有人可以帮我一个简单的代码,该代码将列表作为输出转换为字符串转换为列表吗? The list is NOT like this: 列表不是这样的:

a = u"['a','b','c']"

but the variable is like this: 但是变量是这样的:

a = '[a,b,c]'

So, 所以,

list(a)

would yield the following output 将产生以下输出

['[', 'a', ',', 'b', ',', 'c', ']']

instead I want the input to be like this: 相反,我希望输入是这样的:

['a', 'b', 'c']  

I have even tried using the ast.literal_eval() function - on using which I got a ValueError exception stating the argument is a malformed string. 我什至尝试使用ast.literal_eval()函数-在该函数上我遇到了ValueError异常,指出参数是格式错误的字符串。

There is no standard library that'll load such a list. 没有标准库会加载此类列表。 But you can trivially do this with string processing: 但是您可以通过字符串处理来简单地做到这一点:

a.strip('[]').split(',')

would give you your list. 会给你你的清单。

str.strip() will remove any of the given characters from the start and end; str.strip()将从开头和结尾删除任何给定的字符; so it'll remove any and all [ and ] characters from the start until no such characters are found anymore, then remove the same characters from the end. 因此它将从开头删除所有[]字符,直到不再找到此类字符为止,然后从结尾删除相同的字符。 That suffices nicely for your input sample. 这足以满足您的输入样本要求。

str.split() then splits the remainder (minus the [ and ] characters at either end) into separate strings at any point there is a comma: 然后, str.split()在出现逗号的任何点将其余部分(减去两端的[]字符)分成单独的字符串:

>>> a = '[a,b,c]'
>>> a.strip('[]')
'a,b,c'
>>> a.strip('[]').split(',')
['a', 'b', 'c']

Let us use hack. 让我们使用hack。

import string

x = "[a,b,c]"

for char in x:
    if char in string.ascii_lowercase:
        x = x.replace(char, "'%s'" % char)

# Now x is "['a', 'b', 'c']"
lst = eval(x)

This checks if a character is in the alphabet(lowercase) if it is, it replaces it with a character with single quotes around it. 这会检查一个字符是否在字母(小写)中,是否将其替换为带有单引号的字符。

Why not use this solution ?: 为什么不使用此解决方案?:

  • Fails for duplicate elements 重复元素失败
  • Fails for elements with more than single characters. 包含多个字符的元素失败。
  • You need to be careful about confusing single quote and double quotes 您需要注意不要混淆单引号和双引号

Why use this solution ?: 为什么使用此解决方案?:

  • There are no reasons to use this solution rather than Martijn's. 没有理由而不是Martijn的理由使用此解决方案。 But it was fun coding it anyway. 但是无论如何编码还是很有趣的。

I wish you luck in your problem. 希望您能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM