Python列表中的命名元素

时间:2016-04-22 07:37:32

标签: python

在PHP中,我可以在列表中命名元素,如:

<?php
    list($name,$address,$home) = array("Alex","Taiwan","Vietnam");
    echo $address."\n";
?>

输出:台湾

它在Python中是否可以正常工作?我厌倦了这样做:

list = ["Alex","Taiwan","Vietnam"]
print list[1] 

4 个答案:

答案 0 :(得分:6)

您可以使用拆包。

name, city, country = ["Alex","Taiwan","Vietnam"]
print name

在Python3中,您可以使用*运算符执行更多操作。

a, *b, c = [1, 2, 3, 4, 5] # a = 1, b = [2, 3, 4], c = 5

有关更多概括,请参阅PEP 448 -- Additional Unpacking Generalizations

答案 1 :(得分:2)

模块collections中的

名称元组也很有用:

>>> import collections
>>> Data = collections.namedtuple("Data", "name address home")
>>> Data('Alex', 'Taiwan', 'Vietnam')
>>> d = Data('Alex', 'Taiwan', 'Vietnam')
>>> d.name
'Alex'
>>> d.address
'Taiwan'
>>> d.home
'Vietnam'

答案 2 :(得分:1)

您可以创建自定义namedtuple数据类型:

from collections import namedtuple

# create a new data type (internally it defines a class ContactData):
ContactData = namedtuple("ContactData", ["name", "city", "state"])

# create an object as instance of our new data type
alex = ContactData("Alex", "Taiwan", "Vietnam")

# access our new object
print(alex)             # output: ContactData(name='Alex', city='Taiwan', state='Vietnam')
print(alex.city)        # output: Taiwan
print(alex[1])          # output: Taiwan
alex[0] = "Alexander"   # set new value
print(alex.name)        # output: Alexander

答案 3 :(得分:0)

听起来你真的想要一本字典:

d = {'name': 'Alex', 'address': 'Taiwan', 'home': 'Vietnam'}
print d['address']

如果您需要有序列表,您可以制作一个有序的字典并在其上调用值()。

import collections
d = collections.OrderedDict({'name': 'Alex', 'address': 'Taiwan', 'home': 'Vietnam'})
d.values()