我怎样才能简化“for x in a for y in b for z in c ...”与无序?
#!/usr/bin/python
#
# Description: I try to simplify the implementation of the thing below.
# Sets, such as (a,b,c), with irrelavant order are given. The goal is to
# simplify the messy "assignment", not sure of the term, below.
#
#
# QUESTION: How can you simplify it?
#
# >>> a=['1','2','3']
# >>> b=['bc','b']
# >>> c=['#']
# >>> print([x+y+z for x in a for y in b for z in c])
# ['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']
#
# The same works with sets as well
# >>> a
# set(['a', 'c', 'b'])
# >>> b
# set(['1', '2'])
# >>> c
# set(['#'])
#
# >>> print([x+y+z for x in a for y in b for z in c])
# ['a1#', 'a2#', 'c1#', 'c2#', 'b1#', 'b2#']
#BROKEN TRIALS
d = [a,b,c]
# TRIAL 2: trying to simplify the "assignments", not sure of the term
# but see the change to the abve
# print([x+y+z for x, y, z in zip([x,y,z], d)])
# TRIAL 3: simplifying TRIAL 2
# print([x+y+z for x, y, z in zip([x,y,z], [a,b,c])])
[更新]缺少一件事,如果你真的有for x in a for y in b for z in c ...
,即任意数量的结构,写作product(a,b,c,...)
很麻烦。假设您有一个列表列表,例如上面示例中的 d
。你能简单点吗? Python 让我们使用 *a
对列表进行解包
,并使用 **b
进行字典评估,但这只是表示法。任意长度的嵌套 for 循环和此类怪物的简化超出了 SO,需要进一步研究 此处。我想强调的是,标题中的问题是开放式的,所以如果我接受问题,请不要被误导!
#!/usr/bin/python
#
# Description: I try to simplify the implementation of the thing below.
# Sets, such as (a,b,c), with irrelavant order are given. The goal is to
# simplify the messy "assignment", not sure of the term, below.
#
#
# QUESTION: How can you simplify it?
#
# >>> a=['1','2','3']
# >>> b=['bc','b']
# >>> c=['#']
# >>> print([x+y+z for x in a for y in b for z in c])
# ['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']
#
# The same works with sets as well
# >>> a
# set(['a', 'c', 'b'])
# >>> b
# set(['1', '2'])
# >>> c
# set(['#'])
#
# >>> print([x+y+z for x in a for y in b for z in c])
# ['a1#', 'a2#', 'c1#', 'c2#', 'b1#', 'b2#']
#BROKEN TRIALS
d = [a,b,c]
# TRIAL 2: trying to simplify the "assignments", not sure of the term
# but see the change to the abve
# print([x+y+z for x, y, z in zip([x,y,z], d)])
# TRIAL 3: simplifying TRIAL 2
# print([x+y+z for x, y, z in zip([x,y,z], [a,b,c])])
[Update] A thing missing, what about if you really have for x in a for y in b for z in c ...
, i.e. arbirtary amount of structures, writing product(a,b,c,...)
is cumbersome. Suppose you have a list of lists such as the d
in the above example. Can you get it simpler? Python let us do unpacking
with *a
for lists and the dictionary evaluation with **b
but it is just the notation. Nested for-loops of arbitrary-length and simplification of such monsters is beyond SO, for further research here. I want to stress that the problem in the title is open-ended, so do not be misguided if I accept a question!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个
Try this
编辑:
您可以在很多事情上使用产品,就像您也想要的那样
edit:
you can use product on a bunch of things like you would like to also