简体   繁体   English

Python数组变量分配

[英]Python Array Variable Assign

I have the following array in Python in the following format: 我在Python中使用以下格式的以下数组:

Array[('John', '123'), ('Alex','456'),('Nate', '789')]

Is there a way I can assign the array variables by field as below? 有没有一种方法可以按如下所示按字段分配数组变量?

Name = ['john', 'Alex', 'Nate']
ID = ['123', '456', '789']

In the spirit of "explicit is better than implicit": 本着“明确胜于隐含”的精神:

data = [('John', '123'), ('Alex', '456'), ('Nate', '789')]

names = [x[0] for x in data]
ids = [x[1] for x in data]


print(names) # prints ['John', 'Alex', 'Nate']
print(ids)  # prints ['123', '456', '789']

Or even, to be even more explicit: 甚至更明确地说:

data = [('John', '123'), ('Alex', '456'), ('Nate', '789')]
NAME_INDEX = 0
ID_INDEX = 1

names = [x[NAME_INDEX] for x in data]
ids = [x[ID_INDEX] for x in data]

this is a compact way to do this using zip : 这是使用zip的紧凑方法:

lst = [('John', '123'), ('Alex','456'),('Nate', '789')]

name, userid = list(zip(*lst))

print(name)   # ('John', 'Alex', 'Nate')
print(userid)  # ('123', '456', '789')

note that the results are stored in (immutable) tuple s; 注意结果存储在(不可变的) tuple s中; if you need (mutatble) list s you need to cast. 如果需要(可变) list则需要强制转换。

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

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