這裏是我的問題:我有一個字典在python如:如何避免兩個循環在這裏蟒蛇
a = {1:[2, 3], 2:[1]}
我想輸出:
1, 2
1, 3
2, 1
我在做什麼是
for i in a:
for j in a[i]:
print i, j
所以有沒有更簡單的方法來避免兩個循環,或者這是最簡單的方法呢?
這裏是我的問題:我有一個字典在python如:如何避免兩個循環在這裏蟒蛇
a = {1:[2, 3], 2:[1]}
我想輸出:
1, 2
1, 3
2, 1
我在做什麼是
for i in a:
for j in a[i]:
print i, j
所以有沒有更簡單的方法來避免兩個循環,或者這是最簡單的方法呢?
您擁有的代碼大概和它一樣好。一個小規模的改善可能會遍歷字典的項目外循環,而不是做索引:
for i, lst in a.items() # use a.iteritems() in Python 2
for j in lst:
print("{}, {}".format(i, j))
夫婦使用列表理解,如果你想避免明確的for循環的替代品。
#1方法
# Python2.7
for key, value in a.iteritems(): # Use a.items() for python 3
print "\n".join(["%d, %d" % (key, val) for val in value])
#2方法 - 與列表內涵
print "\n".join(["\n".join(["%d, %d" % (key, val) for val in value]) for key, value in a.iteritems()])
雙方將輸出一個更奇特的方式
1, 2
1, 3
2, 1
字符串格式在這裏是一個更好的主意。 –
@AshwiniChaudhary - 感謝您的建議。 – sidi
記住在Python, Readability counts.
,理想情況@ Blckknght的解決方案就是你應該向前看的方向,但是從技術上看你的問題是一個POC,你可以將你的表達式重寫爲一個循環,這裏有一個解決方案。
但需要注意,如果你婉;噸你的代碼是可讀的,記得Explicit is better than implicit.
>>> def foo():
return '\n'.join('{},{}'.format(*e) for e in chain(*(izip(cycle([k]),v) for k,v in a.items())))
>>> def bar():
return '\n'.join("{},{}".format(i,j) for i in a for j in a[i])
>>> cProfile.run("foo()")
20 function calls in 0.000 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <pyshell#240>:1(foo)
5 0.000 0.000 0.000 0.000 <pyshell#240>:2(<genexpr>)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
10 0.000 0.000 0.000 0.000 {method 'format' of 'str' objects}
1 0.000 0.000 0.000 0.000 {method 'items' of 'dict' objects}
1 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects}
>>> cProfile.run("bar()")
25 function calls in 0.000 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <pyshell#242>:1(bar)
11 0.000 0.000 0.000 0.000 <pyshell#242>:2(<genexpr>)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
10 0.000 0.000 0.000 0.000 {method 'format' of 'str' objects}
1 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects}
你有什麼可能是因爲它得到明確。唯一的問題是,它不會在輸出中產生逗號,但這是微不足道的修復。 – NPE
從循環的角度來看,它並沒有變得更簡單,另一方面,我寧願在a.iteritems()中寫'for vals:vals ...'爲' – bereal
您可能想切換到'對於排序後的(a):' - 現在你的代碼不一定會按照'i'的順序遞增結果。雖然這可能沒有關係。 – DSM