简体   繁体   中英

How to create a integer array?

I tried list

new=[]
new=input()
print(new)

gives me a string as default. How to find the second largest integer from that? I have tried other answers that was found in this site but nothing worked for me.

do not compare strings when you want to compare integers! you need to convert those strings to integers:

in_str = '243 3443 6543 43 546'
ints = [int(i) for i in in_str.split()]
ints.sort(reverse=True)
print(ints[1])  # 3443

( '9' > '10' is True when comparing strings).

You can do it like this:

new = []
new = list(map(int, input().split(' ')))
new.sort()
print(new[-2])

It assumes that your input values are separeted by ' '. For example:

6 5 4 3 7 8

map() maps your strings into integers, which returns map-object. Then you can invoke a list() on it to get a list. After sorting you can get penultimate element by accessing [-2] .

您可以使用heapq模块进行映射,先更改为int,然后再获取第二大的int。

new = heapq.nlargest(2, map(int, new))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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