因此,基本上,我从用户处使用.hidden{
display:none;
}
取n值,然后从一行获取n个整数输入(假设我的输入为<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<div class="timeit" data-start="2019-02-15" data-end="2019-07-25 23:59">
This content will be shown between the dates in data attributes
</div>
,他们写了n = int(input("number of boats"))
,我只使用前两个数字2 6 3 6 4 7 4
),并将其附加到列表中(我之前将其定义为2
)。我想将它们作为整数而不是列表中的字符串。我该怎么办?
编辑:
好的,也许我的措辞不是最好的,所以我将尝试以不同的方式解释。我正在从.txt文件中输入内容,该文件具有:
2 6
开头的mylist = []
确定有多少条船,例如3
23 56
36 48
46 97
是第一条船的值。我想输入确定多少条船的输入,然后将所有值作为输入并将它们全部放入一个列表3
中。请注意,我必须使用输入而不是文件读取,因为将测试不同的值。我需要将这些值作为整数,以便不能将每一行都当作字符串。
答案 0 :(得分:1)
您可以尝试这样。
注意::我认为,无需为
n
取明确的值。
>>> import re
>>>
>>> s = '12 34 56 34 45'
>>> l = re.split(r'\s+', s)
>>> l
['12', '34', '56', '34', '45']
>>>
>>> [int(n) for n in l]
[12, 34, 56, 34, 45]
>>>
>>> # Using the above concept, it can be easily done without the need of explicit n (that you are taking)
...
>>> mylist = [int(n) for n in re.split('\s+', input("Enter integers (1 by 1): ").strip())]
Enter integers (1 by 1): 12 34 56 67 99 34 4 1 0 4 1729
>>>
>>> mylist
[12, 34, 56, 67, 99, 34, 4, 1, 0, 4, 1729]
>>>
>>> sum(mylist)
2040
>>>
答案 1 :(得分:1)
您应该尝试以下代码:
n = int(input("number of boats:"))
mylist = []
for _ in range(n): # Taking n lines as input and add into mylist
mylist.extend(list(map(int, input().rstrip().split())))
print("mylist is:", mylist)
输出为:
number of boats:3
23 56
36 48
46 97
mylist is: [23, 56, 36, 48, 46, 97]
答案 2 :(得分:1)
您可以尝试的一种方法:
numlist = []
n = stdin.readline()
for _ in range(int(n)):
numlist.extend(stdin.readline().split())
stdout.write(str(numlist))
此方法的输出:
2
1 2
3 4 5
此方法花费的时间:
import timeit
setup = "from sys import stdin,stdout"
statement = '''
numlist = []
n = stdin.readline()
for _ in range(int(n)):
numlist.extend(stdin.readline().split())
stdout.write(str(numlist))
'''
print (timeit.timeit(setup = setup,
stmt = statement,
number = 1) )
执行所需时间的输出:
2
1 2
3 4 5
['1', '2', '3', '4', '5']7.890089666
答案 3 :(得分:0)
如果要输入n个输入,则可以执行以下操作:
boats = '2 6 3 6 4 7 4'
n = int(input("number of boats"))
boats = list(map(int, boats.split(' ')))
mylist = boats[:n]
如果该主意是使用带有值的字符串,并让用户决定该字符串的编号如何使您拥有,请执行以下操作:
{{1}}