首页 > 解决方案 > 为什么字符串在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']

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

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

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

标签: python

解决方案


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

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

想必这不是你想要的。


推荐阅读