0

我需要一些帮助来遍历列表列表。我还在学习 Python。

我有一个整数列表,这些整数是更多整数的列表。

例子:

itemWalmart= "food","bread"
itemCostco= "furniture","electronics"
superMarket= walmart,costco

我需要创建一个循环列出项目 + superMarket.Name ,我的问题是当我们向列表中添加更多超级市场和更多项目时。

我想创建一个循环,即使列表增长它也会这样做,所以它会遍历每一个。

列表更大的示例:

itemWalmart= "food","bread"
itemCostco= "furniture","electronics"
itemSoriana= "milk","chocolate"
superMarket= itemWalmart,itemCostco,itemSoriana

我正在尝试的是:

itemWalmart= "food","bread"
itemCostco= "furniture","electronics"
superMarket= itemWalmart,itemCostco

print superMarket

for i in superMarket:
    print i + superMarket 

我明白了:

# (('food', 'bread'), ('furniture', 'electronics'))
# ('food', 'bread', ('food', 'bread'), ('furniture', 'electronics'))
# ('furniture', 'electronics', ('food', 'bread'), ('furniture', 'electronics'))

我想得到这个:

"food","bread" , itemWalmart
"furniture","electronics" , itemCostco

谢谢

4

4 回答 4

5

你会更容易使用字典

markets = {}

markets['Walmart'] = "food","bread"
markets['Costco'] = "furniture","electronics"

for k,v in markets.iteritems():  #use items if you are using python 3x
    print k,v
于 2013-04-08T17:02:14.683 回答
1
itemWalmart= "food","bread"
itemCostco= "furniture","electronics"
superMarketItems= itemWalmart,itemCostco
superMarketNames = "walmart","costco"

for items,name in zip(superMarketItems,superMarketNames):
  print "Items:",items," Found@",name
于 2013-04-08T17:03:53.957 回答
0

不幸的是,你不能用列表来做到这一点。itemWalmart是一个变量名,并且没有强附加到变量。(并且不可检索,特别是因为它已被复制到i)。

我建议使用字典:

markets={}
markets['walmart']=('food','bread')
markets['costco']='furniture,electronics'

for key,value in markets.iteritems():
   print (key,value)

如果您真的想使用列表,请将市场名称与列表一起存储。

itemWalmart= "food","bread","itemWalmart"
itemCostco= "furniture","electronics","itemCostco"
superMarket= itemWalmart,itemCostco

print superMarket

for i in superMarket:
    print i
于 2013-04-08T17:07:00.567 回答
0

我不知道这是否可行,但试试这个,我不知道 python,但我认为这个逻辑可行

for i in superMarket: for x in superMarket[i]: print superMarket[i][x] print superMarket

我不确定如何在 python 中添加“以进行回显

于 2013-04-08T17:08:11.633 回答