Python-使用forloop或while循环查找列表中的最大数

izkcnapc  于 2023-03-09  发布在  Python
关注(0)|答案(2)|浏览(123)

基本上,我们给出了一个数字列表,并要求我们写一个算法,以找到列表中的最大数字,注意:数字没有按顺序排列,可能包含小数和负数。这必须使用python 3.2.3中的循环语句来完成。

alist=[3,10,90,5,-2,4,18,45,100,1,6]
largest=int()
for large in alist:
    if large >= large+1:
       largest=large
print(largest)
flmtquvp

flmtquvp1#

还有一个内置函数叫做max...工作起来很有魅力

ctehm74n

ctehm74n2#

这个问题是9年前提出的,但我给出我的答案,因为这个问题今天仍然相关
我们可以对数字和字符串都这样做
A)查找给定列表中的最大***号***:

your_list = [54, 26, 29, 48, 56, 32, 15, 17]
largest_num = -99999999 # Any value below zero is ok if you know there 
                        # are larger numbers in the list
    
for i in your_list:     # Checking every item in the list
    print("current number:", i) # Printing every item in the list 
                                # regardless of their value
    if i > largest_num: # Is it larger than -99999999?!
        largest_num = i # then value of largest number should be equal 
                        # to the value of i(as integer) 
print("largest number:",largest_num) # Let's print the result when 
                                     #  we're done

B)查找给定列表中最大的***字符串***:

my_list = ["a", "b", "c", "A", "B", "C", " "]
largest_str = my_list[0]
for i in my_list:
    print("current str:", i)
    if i > largest_str:
        largest_str = i

print("largest_str:", largest_str)

相关问题