简体   繁体   English

在Python中将字符串转换为List

[英]Converting a String to List in Python

I'm trying to create a list from arguments I receive in a url. 我正在尝试从我在网址中收到的参数创建一个列表。

eg I have: 我有:

 user.com/?users=0,1,2

Now when I receive it in the request it comes as a string. 现在,当我在请求中收到它时,它以字符串形式出现。 I want to make a list out of "0,1,2" [0,1,2] 我想列出“0,1,2”[0,1,2]的清单

Use the split method. 使用split方法。 Example: 例:

>>> "0,1,2".split(",")
['0', '1', '2']

Or even, 甚至,

>>> [int(x) for x in "0,1,2".split(",")]
[0, 1, 2]

This question was originally tagged Django, so I'll proceed with that in mind. 这个问题最初被标记为Django,所以我将继续考虑这一点。

Inside your view function, the request object has a GET attribute that is an instance of a QueryDict . 在view函数中, request对象具有GET属性,该属性是QueryDict的一个实例。 If you always know that you are going to get a comma separated list of integers for the key "users", you could do something like this in your view function: 如果您始终知道要为关键字“users”获取逗号分隔的整数列表,则可以在视图函数中执行以下操作:

users_list = request.GET('users', "").split(',')

That will give you a list of strings, or an empty list if "users" wasn't supplied in GET. 这将为您提供字符串列表,如果GET中未提供“users”,则为空列表。 If you wanted a list of integers you could process it further with a list comprehension: 如果你想要一个整数列表,你可以用列表理解进一步处理它:

users_list = [int(x) for x in users_list]
import ast
x=ast.literal_eval('0,1,2')
print(x)
# (0, 1, 2)

ast.literal_eval is like eval , but completely safe since it restricts the string to literals such as strings, numbers, tuples, lists, dicts, booleans and None . ast.literal_evaleval类似,但完全安全,因为它将字符串限制为文字,如字符串,数字,元组,列表,dicts,布尔值和None

Another alternative, not yet mentioned, is to use map : 另一个尚未提及的替代方案是使用map

x=map(int,'0,1,2'.split(','))

To go from "0,1,2" to ['0','1','2'] its just "0,1,2".split(",") 要从“0,1,2”变为['0','1','2'],它只是"0,1,2".split(",")

So if you have it in a variable users , then users.split(",") will give you the list. 因此,如果您在变量users拥有它,那么users.split(",")将为您提供列表。

If you need them as ints instead of strings, it would be [int(x) for x in users.split(',')] . 如果你需要它们作为int而不是字符串,那么[int(x) for x in users.split(',')] ,它将是[int(x) for x in users.split(',')]

To convert the string to a list, use split . 要将字符串转换为列表,请使用split

To convert the list of strings to a list of integers, use a list comprehension with int . 要将字符串列表转换为整数列表,请使用带有int的列表int

So putting it all together, it looks something like this: 所以把它们放在一起,它看起来像这样:

s = '0,1,2'
l = [int(x) for x in s.split(',')]

Results: 结果:

[1, 2, 3]

You can use following code: 您可以使用以下代码:

s = 'user.com/?users=0,1,2'
s.rpartition('?users=')[2].split(',')

You have eval to convert string to "real code": 你有eval将字符串转换为“真实代码”:

Example: 例:

>>> l = u"[('0','None'),('2','Taxable Goods'),('4','Shipping')]"
>>> type(l)
<type 'unicode'>

>>> t = eval(l)
>>> type(t)
<type 'list'>

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

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