为什么在python中将字符串拆分为字符

2024-09-27 07:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我编写的代码:

def comb(self, rows, cols):
    return [s+t for s in a for t in b]

如果rowscols的值为

rows = ['abc','efg']
cols = ['123','456']

预期输出:['abc123','abc456,'efg123','efg456']

程序输出:['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']

我是Python编程新手。你能帮我了解发生了什么事吗?我已经修复了输出,但我想了解为什么会发生这种情况


Tags: 代码inselfforreturndefrowsabc
3条回答

将其更改为:

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))

输出:

['abc123', 'abc456', 'efg123', 'efg456']

要理解您的列表理解正在做什么,您可以这样重写它:

results = []
for s in a:
    for t in b:
        results.append(s+t)

想必那不是你想要的

尝试使用zip()函数:

>>> 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()函数将rows中的每个值与cols中的每个值配对

>>> list(zip(rows, cols))
[('abc', '123'), ('efg', '456')]

另一方面,[s+t for s in a for t in b]是一个嵌套的for循环,其中a的迭代嵌套在b的迭代中

相关问题 更多 >

    热门问题