【问题标题】:How do I iterate through a list to print each variable in the list? [closed]如何遍历列表以打印列表中的每个变量? [关闭]
【发布时间】:2014-09-12 06:27:24
【问题描述】:

如果我有这个作为我的代码:

import sys
from sys import argv
if len(sys.argv) == 7:
    a,b,c,d,e,f,g = argv
    c_list = c.split(',')
    d_list = d.split(',')
    if len(c_list) == len(d_list):
        print b
    elif len(d_list) == len(c_list):
        print b
    else:
        sys.exit()
    for c in c_list:
        if len(c_list) == len(d_list):
            print c
        else:
            sys.exit()
    for d in d_list:
        if len(d_list) == len(c_list):
            print d
        else:
            sys.exit()
    print e
    print f
    print g

else:
    a,b,c,d,e,f = argv
    c_list = c.split(',')
    d_list = d.split(',')
    if len(c_list) == len(d_list):
        print b
    elif len(d_list) == len(c_list):
        print b
    else:
        sys.exit() 
    for c in c_list:
        if len(c_list) == len(d_list):
            print c
        else:
            sys.exit()
    for d in d_list:
        if len(d_list) == len(c_list):
            print d
        else:
            sys.exit()
    print e
    print f

它允许我将以下内容传递给 argv:

a b c,c1,c2 d,d1,d2 e f g

我的其他代码导致此列表打印为

    a 
    b 
    c
    c1
    c2
    d
    d1
    d2
    e
    f
    g

但是,我希望它打印以下内容:

    a
    b
    c
    d
    e 
    f
    g
    a
    b
    c1
    d1
    e
    f
    g

等等等等。我该怎么做?如果这看起来超级基本,我很抱歉。作为一名高中新生,我仍在试图弄清楚复杂的编码世界是如何运作的。

【问题讨论】:

  • 我不明白你想要的输出背后的逻辑。你怎么知道的?您究竟希望它如何组织?您需要向我们展示您的打印代码;否则我们不可能知道错误是什么。
  • 这不是有效的 Python 语法。这是什么a b c d e f g = argv?您的用户输入来自哪里?
  • @TheSoundDefense 我继续添加我的整个代码
  • @user3861531 仍然不完全清楚您要实现的目标,但可能类似于thisthis
  • @jonrsharpe 不是一个接一个地打印不同的 c 值,而是希望它再次打印整个列表,每次打印都经过每个额外的 c 值。

标签: python list printing iteration


【解决方案1】:

根据您的描述,我认为您想要这样的东西:

>>> a = 1
>>> b = 2
>>> c = [3, 4, 5]
>>> d = [6, 7, 8]
>>> for cx, dx in zip(c, d):
        for item in (a, b, cx, dx):
            print(item)
        print("---")


1
2
3
6
---
1
2
4
7
---
1
2
5
8
---

【讨论】:

  • 是的,这正是我所需要的,谢谢
猜你喜欢
  • 1970-01-01
  • 2019-12-30
  • 2017-12-10
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多