我在Python中使用以下格式的以下数组:
Array[('John', '123'), ('Alex','456'),('Nate', '789')]
有没有一种方法可以按如下所示按字段分配数组变量?
Name = ['john', 'Alex', 'Nate']
ID = ['123', '456', '789']
答案 0 :(得分:1)
本着“明确胜于隐含”的精神:
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']
或更确切地说:
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]
答案 1 :(得分:0)
这是使用zip
的紧凑方法:
lst = [('John', '123'), ('Alex','456'),('Nate', '789')]
name, userid = list(zip(*lst))
print(name) # ('John', 'Alex', 'Nate')
print(userid) # ('123', '456', '789')
请注意,结果存储在(不可变的)tuple
s中;如果您需要{mutable)list
,则需要投射。