سؤال

#!/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 في المثال أعلاه. هل يمكنك الحصول عليها أكثر بساطة؟ بيثون دعنا نفعل unpacking مع *a للقوائم وتقييم القاموس مع **b لكنه مجرد تدوين. متداخل من أجل الطول التعسفي وتبسيط مثل هذه الوحوش هو أبعد من ذلك ، لمزيد من البحث هنا. أريد أن أؤكد أن المشكلة في العنوان مفتوحة ، لذا لا تكون مضللاً إذا قبلت سؤالاً!

هل كانت مفيدة؟

المحلول

>>> from itertools import product
>>> a=['1','2','3']
>>> b=['bc','b']
>>> c=['#']
>>> map("".join, product(a,b,c))
['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']

تعديل:

يمكنك استخدام المنتج على مجموعة من الأشياء التي ترغب في ذلك أيضًا

>>> list_of_things = [a,b,c]
>>> map("".join, product(*list_of_things))

نصائح أخرى

جرب هذا

>>> import itertools
>>> a=['1','2','3']
>>> b=['bc','b']
>>> c=['#'] 
>>> print [ "".join(res) for res in itertools.product(a,b,c) ]
['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top