简体   繁体   English

Python:访问列表组合中的列表元素

[英]Python: accessing elements of a list within a combination of lists

I am new to python and I have spent hours trying to figure out the following problem. 我是python的新手,我花了数小时试图找出以下问题。 I have an object that looks like this 我有一个看起来像这样的物体

>> new_list=['abscd','qrtye']['fghtj', 'wert']...more lists
>> type(new_list)

<type 'list'>
<type 'list'>
...

I would like to access each string within each list. 我想访问每个列表中的每个字符串。 I tried a for-loop and to use .split() as in: 我尝试了for循环并使用.split(),如下所示:

>> for l in new_list:
>>     l.split() 

but I can't access the two strings separately within list l. 但我无法在列表l中单独访问两个字符串。 Any help will be appreciated.Thanks! 任何帮助将不胜感激。谢谢!

I'm guessing you have an iterable which yields 2-element lists when iterating. 我猜您有一个可迭代的对象,在迭代时会生成2个元素的列表。 If so, you can unpack those 2-element lists in your for loop: 如果是这样,您可以在for循环中解压缩那些2元素列表:

>>> data = ["foo","bar"],["baz","qux"]
>>> for s1,s2 in data:
...     print s1, "Hello", s2
... 
foo Hello bar
baz Hello qux

You have to put your lists into a 'parent' list, and there you go, it's something like: 您必须将您的列表放入“父”列表中,然后就可以了,就像这样:

new_list = [['abscd', 'qrtye'], ['fghtj', 'wert']]
for sub_list in new_list:
    for string in sub_list:
        # do something with string

Or with generator expressions: 或使用生成器表达式:

for string in (string for sub_list in new_list for string in sub_list):
    # do something with string

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

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