迭代两个列表并组合项目

时间:2017-03-03 18:10:26

标签: python list iteration

我想迭代并组合两个列表中的项目。但它必须从列表1中的第1项开始,并迭代并与列表2中的所有项目结合。

Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.

我想要的是:

“/合伙人/路径/ 1 / DIR1” “/合作伙伴/路/ 1 / DIR2” “/合伙人/路径/ 1 / DIR3”

“/合伙人/路径/ 2 / DIR1” “/合作伙伴/路/ 2 / DIR2” “/合伙人/路径/ 2 / DIR3”

“/合伙人/路径/ 3 / DIR1” “/合作伙伴/路/ 3 / DIR2” “/合伙人/路径/ 3 / DIR3”

4 个答案:

答案 0 :(得分:2)

如果您需要列表中的结果,则可以将itertools.product与列表理解结合使用:

from itertools import product
[d + f for d, f in product(partner_paths, scr_dirs)]

#['/partner/path/1/dir1',
# '/partner/path/1/dir2',
# '/partner/path/1/dir3',
# '/partner/path/2/dir1',
# '/partner/path/2/dir2',
# '/partner/path/2/dir3',
# '/partner/path/3/dir1',
# '/partner/path/3/dir2',
# '/partner/path/3/dir3']

或者@vaultah建议,这也应该有效:

[p + d for p in partner_paths for d in scr_dirs]

答案 1 :(得分:2)

for循环无法解决问题吗?

for p_path in partner_paths:
    for s_dir in scr_dirs:
       fpath = p_path + s_dir
       print fpath

答案 2 :(得分:1)

如果您想要2D输出,此代码也可以正常工作:

final_output = []
for p_path in partner_paths:
  paths = []
  for s_dir in scr_dirs:
    fpath = p_path + s_dir
    paths.append(fpath)
  output_list.append(paths)

print (final_output)

答案 3 :(得分:0)

partner_paths = ["/partner/path/1", "/partner/path/2", "/partner/path/3"]
scr_dirs = ["/dir1", "/dir2", "/dir3"]
fpath = []
for p_path in partner_paths:
    for s_dir in scr_dirs:
        fpath.append(p_path + s_dir)

print(fpath)