[英]Why is the string split into characters in python
以下是我写的代码:
def comb(self, rows, cols):
return [s+t for s in a for t in b]
如果rows
和cols
的值是
rows = ['abc','efg']
cols = ['123','456']
预期 output: ['abc123','abc456,'efg123','efg456']
程序 output: ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']
我是 Python 编程的新手。 你能帮我理解发生了什么吗? 我已经修复了 output 但我想了解为什么会这样。
要了解您的列表理解在做什么,您可以像这样重写它:
results = []
for s in a:
for t in b:
results.append(s+t)
想必这不是你想要的。
尝试使用zip()
function:
>>> rows = ['abc','efg']
>>> cols = ['123','456']
>>> def comb(rows, cols):
return [r+c for r, c in zip(rows, cols)]
>>> comb(rows, cols)
['abc123', 'efg456']
zip()
function 本质上是将rows
中的每个值与cols
中的每个值配对。
>>> list(zip(rows, cols))
[('abc', '123'), ('efg', '456')]
另一方面, [s+t for s in a for t in b]
是一个嵌套for
循环,其中a
的迭代嵌套在b
的迭代中。
将其更改为:
rows = ['abc','efg']
cols = ['123','456']
def comb(rows, cols):
return [s+t for s in rows for t in cols]
print(comb(rows,cols))
output:
['abc123', 'abc456', 'efg123', 'efg456']
itertools
库是一个流行的cols
标准库,其中包含许多工具,可帮助您迭代组合迭代器的不同方式(例如给定的rows
和列列表)。
import itertools
def comb(rows, cols):
return map(lambda t: t[0] + t[1], itertools.product(rows, cols))
itertools.product
将为您提供一个充满元组的迭代器,它为您提供rows
中条目的所有可能组合作为第一个元素,并将cols
中的条目作为第二个元素。
map
使用lambda
function 将itertools.product
生成的元组中的两个字符串连接成一个字符串,这就是你想要的。
要获得您提到的想要的列表,您可以在 function list()
中包装对map
的调用,以评估map
生成的迭代器到列表中。 仅供参考,对于大型列表,这将是低效的,因为组合子字符串的结果将全部存在于 memory 中,而如果您使用我给您的第一个def comb
提供的迭代器,当您迭代这些迭代器时,您将使用规则生成每个条目,如 go。
这是我的代码中的一个错误,因为我没有将字符串按原样使用,而是将每个字符串用作梳子 function 的输入
def comb(self, rows, cols): return [s+t for s in a for t in b]
行 = ['abc','efg'] 列 = ['123','456']
print [comb(rs, cs) for rs in rows for cs in cols]
所以 output 是 ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']
在此 function 中,它将采用字符串的每个字符,而 output 将是字符的组合而不是字符串。
但感谢您尝试提供帮助。 对此,我真的非常感激。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.