循环通过“锯齿状”列表

时间:2016-02-19 14:17:50

标签: python loops jagged-arrays

所以我有这个清单:

list = ["NYC Football", ["NY Giants","NY Jets"], "NYC Hockey", ["NY Rangers", "NY Islanders", "NJ Devils"]]

我如何遍历此列表并仅打印出来:

NY Giants
NY Jets
NY Rangers
NY Islanders
NJ Devils

3 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

NY Giants
NY Jets
NY Rangers
NY Islanders
NJ Devils

<强>输出

list

旁白:您不应将关键字my_list用作变量名称。在我的示例中,我将其更改为<DataGridTemplateColumn Header="Skills" IsReadOnly="False"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <ListBox ItemsSource="{Binding Skills, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> <ListBox.ItemTemplate> <DataTemplate> <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Command="{Binding Path=DataContext.SaveChangesCommand, RelativeSource={RelativeSource Mode=Self}}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn>

答案 1 :(得分:2)

首先,请不要使用名单列表。您将隐藏内置列表,这将使您迟早难以检测到错误。

作为评论中已经提到的chepner,我强烈建议您将列表转换为字典,以便获得一项干净的运动:团队映射。

>>> lst = ["NYC Football", ["NY Giants","NY Jets"], "NYC Hockey", ["NY Rangers", "NY Islanders", "NJ Devils"]]
>>> teams = dict(zip(*[iter(lst)]*2))
>>> teams
{'NYC Football': ['NY Giants', 'NY Jets'], 'NYC Hockey': ['NY Rangers', 'NY Islanders', 'NJ Devils']}

要参加体育活动,请发出

>>> teams.keys()
['NYC Football', 'NYC Hockey']

要获得团队,请发出

>>> teams.values()
[['NY Giants', 'NY Jets'], ['NY Rangers', 'NY Islanders', 'NJ Devils']]

您也可以使用itertools.chain取消嵌套此列表:

>>> list(chain.from_iterable(teams.values()))
['NY Giants', 'NY Jets', 'NY Rangers', 'NY Islanders', 'NJ Devils']

我认为字典的顺序并不重要。如果是,您可以使用OrderedDict模块中的collections

>>> from collections import OrderedDict
>>> teams = OrderedDict(zip(*[iter(lst)]*2))
>>> for team in chain.from_iterable(teams.values()):
...     print(team)
... 
NY Giants
NY Jets
NY Rangers
NY Islanders
NJ Devils

答案 2 :(得分:0)

循环遍历外部列表,并且仅当项目是列表时,迭代它并打印其项目:

for thing in filter(lambda x: isinstance(x, list)):
    for other in thing:
        print(other)

另一种方式:

CMAC_Init