简体   繁体   English

在 Python 的“for”循环中追加多行数组时遇到问题

[英]Having trouble appending a multi-line array in a `for` loop in Python

Not sure how to word my question.不知道如何表达我的问题。 I'm trying to collect data with input in a for loop and append it every time.我正在尝试通过for循环中的input收集数据,每次都是 append。 I want it to look like this: Each loop of input , I want to enter: SOL $XXX $ZZZ , BTC $XXX $ZZZ , ETH $XXX $ZZZ , etc.我希望它看起来像这样: input的每个循环,我想输入: SOL $XXX $ZZZBTC $XXX $ZZZETH $XXX $ZZZ等。

And I want the finished output to look like this:我希望完成的 output 看起来像这样:

* `BTC 4/12@07:59pm :: $291.42 @ $40,173.45`
* `SOL 4/12@07:59pm :: $267.02 @ $103.28`
* `LTC 4/12@07:59pm :: $220.91 @ $104.82`
* `ETH 4/12@07:59pm :: $177.43 @ $3,031.23`
* `wETH 4/12@07:59pm :: $45.20 @ $3,031.23`
* `Total 4/12@07:59pm :: $1,001.98`

I'll be able to format it, I just can't figure out how to keep appending the input.我将能够格式化它,我只是不知道如何继续附加输入。 I'm sure it'll be something simple that I just can't picture at the moment.我敢肯定这会很简单,我现在无法想象。 Hopefully I worded this well enough for someone to understand my query.希望我的措辞足够好,可以让别人理解我的查询。
Thanks in advance.提前致谢。

So we have 2 issues here.所以我们这里有两个问题。 1 making the for loop, 2 printing stuff out. 1 制作 for 循环,2 打印内容。

For 1 we'll just do a while loop (since we don't know when you'll stop) based on the input:对于 1,我们将根据输入执行一个 while 循环(因为我们不知道您何时停止):

from datetime import datetime
user_input = "not empty"
inputs_list = []
while True:
  user_input = input("What are your coordinates?")
  if user_input == "":
    break
  split_string = user_input.split(" ", 1)
  string_with_date = datetime.now().strftime(
    "{prefix} %m/%d@%I:%M%p {coordinates}".format(prefix=split_string[0], coordinates=split_string[1])
  )
  inputs_list.append(string_with_date)

This will keep looping until you give an empty return to the input call.这将一直循环,直到您对输入调用返回一个空值。 Then we can print all of your results with:然后我们可以打印您的所有结果:

for row in inputs_list:
  print("* `{row}`".format(row=row))

The heavy lifting is done by this part:繁重的工作由这部分完成:

string_with_date = datetime.now().strftime(
    "{prefix} %m/%d@%I:%M%p {coordinates}".format(prefix=split_string[0], coordinates=split_string[1])
  )

We use the split method to cut your inputs at the first space and glue them back together in the strftime argument with the date in between.我们使用 split 方法在第一个空格处剪切您的输入,然后在 strftime 参数中将它们粘在一起,中间有日期。

For more info on strftime or on split , check the documentation linked in this message.有关strftimesplit的更多信息,请查看此消息中链接的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM