循环列表

时间:2013-04-08 16:59:02

标签: python

我需要一些帮助来循环列表列表。我还在学习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 个答案:

答案 0 :(得分:5)

您可以更轻松地使用dictionary

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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:0)

我不知道这是否有效但是试试这个,我不知道python但我觉得这个逻辑会起作用

for superMarket:     对于superMarket中的x [i]:       打印superMarket [i] [x]    打印superMarket

我不知道如何添加“in python for echoing