Python清单2项目符号形式的列表

2024-10-05 14:23:34 发布

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

在python代码中,我有两个列表

myList = ["Example", "Example2", "Example3"]
mySecondList = ["0000", "1111", "2222"]

我需要把这些打印出来,让它们看起来像这样:

- Example 0000
- Example2 1111
- Example3 2222

有没有办法做到这一点?你知道吗


Tags: 代码列表example办法example2mylistexample3mysecondlist
2条回答

是的,找^{}

myList = ["Example", "Example2", "Example3"]
mySecondList = ["0000", "1111", "2222"]

for a, b in zip(myList, mySecondList):
    print("- {} {}".format(a, b))
- Example 0000
- Example2 1111
- Example3 2222

如果列表具有相同的大小,则上述方法将起作用,否则您应该根据所使用的python版本从itertools模块查看^{}^{}

我建议用zip()zip_longest()来回答你的问题。你知道吗

但是,不使用任何built-in模块/函数。您可以通过自己的类似于zip()函数的方法创建自己的“hacky”方法。你知道吗

举个例子:

def custom_zip(a, b, fill=None):
    length = max(len(a), len(b))
    for k in range(length):
        if k > len(a):
            yield fill, b[k]
        elif k > len(b):
            yield a[k], fill
        else:
            yield a[k], b[k]

a = ["Example", "Example2", "Example3"]
b = ["0000", "1111", "2222"]

for k, v in custom_zip(a,b):
    print("- {} {}".format(k, v))

输出:

- Example 0000
- Example2 1111
- Example3 2222

此外,您还可以查看official documentationzip()的等价物。你知道吗

相关问题 更多 >