【问题标题】:How to Loop Through List and Print Each Item But Include Previous with Each Line如何循环遍历列表并打印每个项目但在每行中包含上一个
【发布时间】:2023-02-15 23:36:50
【问题描述】:

所以我现在有这段代码,但问题是它将遍历整个列表并打印为一个。

formatted_conversations = []
for conv in conversations:
    speaker, message = conv
    if len(formatted_conversations) == 0 or formatted_conversations[-1].split(" : ")[0] != speaker:
        formatted_conversations.append(speaker + " : " + message)
    else:
        formatted_conversations[-1] += "\n" + message
conversations=[]
for c in formatted_conversations:
    conversations.append(c.split(" : "))

这是我的示例列表

鲍勃:1

2个

3个

乔:4

5个

6个

所以现在发生的是它自动将 Bob 1,2,3 打印为一个。

但我需要它像这样打印

鲍勃:1

鲍勃:1 2个

鲍勃:1 2个 3个

乔:4

乔:4 5个

乔:4 5个 6个

所以本质上它打印为 3 vs 1 并且它每次都添加以前的列表并在看到新人时切换:

【问题讨论】:

  • 连接到上一项时将\n更改为空格?
  • 在一行上打印为 Bob 1 2 3。我需要将它们分开但包括上一条消息
  • 如果你在自己的行上打印每个列表元素,你就会得到它。

标签: python list


【解决方案1】:

每次附加一条新消息时,您都可以在它之前附加一个新行,只需替换 ' ' 之内:

formatted_conversations[-1] += "
" + message

包括旧的重新追加最后一行

formatted_conversations.append(formatted_conversations[-1])

新代码:

formatted_conversations = []
for conv in conversations:
    speaker, message = conv
    if len(formatted_conversations) == 0 or formatted_conversations[-1].split(" : ")[0] != speaker:
        formatted_conversations.append(speaker + " : " + message)
    else:
        formatted_conversations.append(formatted_conversations[-1])
        formatted_conversations[-1] += " " + message
conversations=[]
for c in formatted_conversations:
    conversations.append(c.split(" : "))

【讨论】:

  • 只是将它们全部打印在同一行上。所以它只是说 bob 1 2 3
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-30
  • 2014-06-29
  • 2011-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多