当前位置: 首页 > 知识库问答 >
问题:

我如何创建一个for循环,让3个列表组合到一个字符串中,一个接一个地在python[复制]

赫连法
2023-03-14
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,10,11,12]
list3 = ["a","b","c","d","e","f"]
text1 = print('this is 1 and 7 and a')
text2 = print('this is 2 and 8 and b')
text3 = print('this is 3 and 9 and c')
text4 = print('this is 4 and 10 and d')

谢谢你,伙计:D

共有3个答案

羊毅庵
2023-03-14

您可以使用zip

list1 = [1,2,3,4,5,6]
list2 = [7,8,9,10,11,12]
list3 = ["a","b","c","d","e","f"]

for a,b,c in zip(list1, list2, list3):
    print(f'This is {a} and {b} and {c}')

输出:

This is 1 and 7 and a
This is 2 and 8 and b
This is 3 and 9 and c
This is 4 and 10 and d
This is 5 and 11 and e
This is 6 and 12 and f
dic = {f'text{i+1}':  f'This is {a} and {b} and {c}'
       for i, (a,b,c) in enumerate(zip(list1, list2, list3))}

输出:

{'text1': 'This is 1 and 7 and a',
 'text2': 'This is 2 and 8 and b',
 'text3': 'This is 3 and 9 and c',
 'text4': 'This is 4 and 10 and d',
 'text5': 'This is 5 and 11 and e',
 'text6': 'This is 6 and 12 and f'}
易超
2023-03-14

试试拉链

for first, second, third in zip(list1, list2, liste):
    print(first, second, third)
凌蕴藉
2023-03-14

假设所有列表长度相同,您可以遍历索引:

for i in range(len(list1)):
    print (f'This is {list[1]} and {list2[i]} and {list3[i]}')
 类似资料:
  • 我有两个字符串str1和str2。我试图用字符把一些字母从一个字符串复制到另一个字符串。我知道我可以使用字符串复制,但我想要一些字符,而不是全部字符。 在Java中,如何将子字符串从一个字符串复制到另一个字符串?

  • 问题内容: 例如,如果我有一个元组列表 如何解开元组并将其重新格式化为一个列表 我认为这也与功能有关,但是我真的不知道该怎么做。请赐教。 问题答案: b = [i for sub in a for i in sub] 这样就可以了。

  • 问题内容: 除了以下内容外,我想要一种有效的方法来在Python中将一个字符串附加到另一个字符串。 有什么好的内置方法可以使用吗? 问题答案: 如果你仅对一个字符串有一个引用,并且将另一个字符串连接到末尾,则CPython现在会对此进行特殊处理,并尝试在适当位置扩展该字符串。 最终结果是将操作摊销O(n)。 例如 过去是O(n ^ 2),但现在是O(n)。 从源(bytesobject.c): 凭

  • 我试图扫描一个整数,并运行一个循环来扫描字符串,直到那个整数。但这段代码跳过了第一个字符串... 有解决办法吗?

  • 我有一个名为Card的类,我有一个for循环: 我想做的是基于for循环创建新实例。例如,我希望名字是card1、card2、card3等等。数字来自for循环。 我试过这个,但似乎不起作用: 谁能告诉我我做错了什么吗? 谢谢 所以我正在使用气垫船充满鳗鱼的解决方案,但我还有另一个问题。 我用的是卡片列表。添加(新卡()),当我尝试使用Card(I)设置名称时,java不允许我这么做。在没有i的情

  • 问题内容: 如何从Python列表中的第一个字符串中获取第一个字符? 看来我可以使用,但不会给我第一个字符。 问题答案: 你几乎是对的。最简单的方法是 但 也可以。 你想 结束 的第一个字符(字符零)后,未 启动 的第一个字符(字符零),这是以后有什么在你的问题的手段的代码。