在列表中
x
我希望在所有可能的排列中将.
和-
替换为列表中的每个['. . ... .'],
['- - -.. -'],
['. - -.. .']
(通过将列表读成字符串)。因此输出可能是
def fun(inputStringList):
message_received = inputStringList
message_received = ' '.join(inputStringList)
for i in range(len(message_received)):
x = 'x'
y = '.'
message = message_received.replace(x, y)
message1 = message.split(",")
print message1
for i in range(len(message_received)):
x = 'x'
y = '-'
message = message_received.replace(x, y)
message2 = message.split(",")
print message2
def funTest():
test = ['x', 'x', 'x..', 'x']
print fun(test)
funTest()
和所有类似的排列。我尝试了以下脚本,但我只能得到两个模式作为输出。
['. . ... .']
['- - -.. -']
输出:
def bad_decorator(cls):
del cls.method
return cls
@bad_decorator
class Test(object):
def method(self):
return 'test method'
print(Test().method()) # AttributeError: 'Test' object has no attribute 'method'
怎么办?
答案 0 :(得分:1)
您希望( x
个字符数).
和-
的产品重复,因此{{1} }。
我使用product('.-', number=number_of_x_characters)
可以轻松插入生成的str.format()
和.
组合:
-
这是一个生成器,循环遍历它:
from itertools import product
def fun(inputStringList):
count = sum(s.count('x') for s in inputStringList)
template = ' '.join(inputStringList).replace('x', '{}')
for replacements in product('.-', repeat=count):
yield template.format(*replacements)