简体   繁体   English

将输入中的多个数字放入一个列表中

[英]Putting multiple numbers from an input into one list

I'm trying to put multiple interest rates from one input into a list.我正在尝试将来自一个输入的多个利率放入一个列表中。 I'm assuming just putting a comma between them wont separate them into different variables in the list?我假设只是在它们之间加一个逗号不会将它们分成列表中的不同变量? Is there a way I can get them all into a list in one input or do i need to run the input multiple times and add one each time?有没有一种方法可以将它们全部放入一个输入的列表中,还是我需要多次运行输入并每次添加一个?

interest_rates_list = []


while True:
    investment = input("Please enter the amount to be invested ")
    periods = input("Please enter the number of periods for investment maturity ")
    if int(periods) < 0:
        break
    interest_rates = input("Please enter the interest rate for each period ")
    interest_rates_list.append(interest_rates)

If you input is something like:如果你输入是这样的:

4 5 12 8 42

then you can simply split it up by space and assign to values list:然后您可以简单地按空格将其拆分并分配给values列表:

values = input().split()

If your input something like 4,5,12 , then you need to use split(',') .如果您的输入类似于4,5,12 ,那么您需要使用split(',')

You can split the input string into several string and then convert it to float .您可以将input string split为多个string ,然后将其转换为float This can be done in one line.这可以在一行中完成。

interest_rates = list(map(float, interest_rates.split(",")))

Here I go a step further, your next move will be to calculate some return based on interest rates, and so you will need float/integer to do so.在这里我 go 更进一步,您的下一步将是根据利率计算一些回报,因此您需要浮点数/整数。

The python string function split can accept a delimiter character and split the input string into a list of values delimited by that character. python 字符串 function 拆分可以接受分隔符并将输入字符串拆分为由该字符分隔的值列表。

interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list = interest_rates.split(",")

If you take the input, you can convert it to a string by using:如果您接受输入,则可以使用以下方法将其转换为字符串:

str(interest_rates)

Let this be variable A So, A = str(interest_rates)让它成为变量 A 所以, A = str(interest_rates)

Now, to seperate each entry of the interest rates, we do:现在,为了分离利率的每个条目,我们这样做:

interest_rates_list = A.split(' ')

This function literally splits the string at all spaces and returns a list of all the broken pieces.这个 function 从字面上将字符串在所有空格处拆分,并返回所有碎片的列表。

NOTE: if you do A.split(*any string or character*) it'll split at the mentioned character.注意:如果您执行A.split(*any string or character*)它将在提到的字符处拆分。 Could be ',' or ';'可以是 ',' 或 ';' or ':', etc.或“:”等。

Now you can iter over the newly formed list and convert all the numbers stored as string to ints or floats by doing现在您可以遍历新形成的列表并将所有存储为字符串的数字转换为整数或浮点数

for i in interest _rates_list:
    i = float(i) #or int(i) based on your requirement

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

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