【发布时间】:2021-11-15 07:47:14
【问题描述】:
这个漂亮的脚本生成给定集合 s 的所有 4 个字符排列,并将它们打印在新行上。
import itertools
s = ('7', '8', '-')
l = itertools.product(s, repeat=4)
print(*l, sep='\n')
示例输出:
...
('9', '-', '7', '8')
('9', '-', '7', '9')
('9', '-', '8', '7')
('9', '-', '8', '8')
('9', '-', '8', '9')
...
我不知道如何删除所有单引号、逗号和左/右括号。
期望的输出:
...
9-78
9-79
9-87
9-88
9-89
...
尝试添加:
c = []
for i in l:
i = i.replace(",", '')
c.append(i)
print(*c, sep='\n')
错误: AttributeError: 'tuple' object has no attribute 'replace'
也试过了:我似乎找不到在哪里放置 print(' '.join()) 逻辑。
【问题讨论】:
-
print(*l, sep='\n')在每一行打印元组,打印时会自动添加括号和逗号。尝试提取元组元素并使用join创建一个字符串
标签: python itertools more-itertools