Python:如何从这种类型的列表中访问数据?
快速 Python 问题:如何从这样的嵌套列表访问数据:
{'album': [u'Rumours'], 'comment': [u'Track 3'], 'artist': [u'Fleetwood Mac'], 'title': [u'Never Going Back Again'], 'date': [u'1977'], 'genre': [u'Rock'], 'tracknumber': [u'03']}
我尝试了 listname[0][0]
但它返回错误: AttributeError: 'int' object has no attribute 'lower'
那么我该怎么做呢?
Quick Python question: How do I access data from a nested list like this:
{'album': [u'Rumours'], 'comment': [u'Track 3'], 'artist': [u'Fleetwood Mac'], 'title': [u'Never Going Back Again'], 'date': [u'1977'], 'genre': [u'Rock'], 'tracknumber': [u'03']}
I tried listname[0][0]
but it returns the error:AttributeError: 'int' object has no attribute 'lower'
So how would I go about doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是一个列表,这是一本字典。对于每个
key,value
对,它采用不可变类型作为键,并采用任何类型作为值。在您的情况下,这是一个以str
类型键和list
作为值的字典。您必须首先从字典中提取列表,然后从列表中提取第一个元素,假设您的意思是:请注意,字典不是类型绑定的并且可以混合类型:
有关字典的更多信息可以在此处找到:
This is not a list, it is a dictionary. It takes an immutable type as key and any type as value for every
key,value
pair. In your case this is a dictionary withstr
type keys andlist
's as values. You must first extract the list from the dictionary, and then the first element from the list, assuming you meant that:Please note that a dictionary is not type-bound and can mix types:
And some more information about dictionaries can be found here: http://docs.python.org/tutorial/datastructures.html#dictionaries
这不是一个列表。这是一本字典。
该字典没有排序,因此无法通过数字索引*访问它。
您必须像这样引用它:
listname['album']
上面将返回一个包含一个元素的列表(恰好是一个列表):
[u'Rumours']
,要访问列表,您可以像往常一样操作。总而言之:
请注意,列表可以包含更多元素,因此您可以像
[0]
、[1]
等那样引用它们。看看 文档 了解更多信息。
*你可以这样做:
我的意思是你不使用基于零的索引,你使用可以是“任何你想要的”的键,并且这个键引用值。
This is not a list. This is a dictionary.
The dictionary is not ordered, and thus it cannot be accessed through a numeric index*.
You must refer to to it like this:
listname['album']
The above will return you a list with one element (which happens to be a list):
[u'Rumours']
, to acces a list, you do as usual.So altogether:
Notice that the list could have more elements, so you would refer them like so
[0]
,[1]
etc.Take a look at the docs for more information.
*You can do:
What I meant is that you don't use zero based indexes, you use keys that can be "whatever you want" and this keys refer to values.