所以我有这个列表和变量:
nums = [14, 8, 9, 16, 3, 11, 5]
big = nums[0]
spot = 0
我对如何实际做到这一点感到困惑。我想用这个练习给我一个开端。我如何在 Python 上做到这一点?
通常,您可以只使用
max(nums)
如果您明确想要使用循环,请尝试:
max_value = None
for n in nums:
if n > max_value: max_value = n
nums = [14, 8, 9, 16, 3, 11, 5]
big = None
spot = None
for i, v in enumerate(nums):
if big is None or v > big:
big = v
spot = i
干得好...
nums = [14, 8, 9, 16, 3, 11, 5]
big = max(nums)
spot = nums.index(big)
这将是实现这一目标的 Pythonic 方式。如果要使用循环,则以当前最大值循环并检查每个元素是否较大,如果是,则分配给当前最大值。
要解决您的第二个问题,您可以使用for
循环:
for i in range(len(list)):
# do whatever
您应该注意,它range()
可以有 3 个参数:start
、end
和step
。Start 是从哪个数字开始(如果未提供,则为 0);开始是包容性的。结束是结束的地方(必须给出);end 是唯一的:如果你这样做range(100)
,它会给你 0-99。步长也是可选的,它表示使用什么间隔。如果未提供 step,则为 1。例如:
>>> x = range(10, 100, 5) # start at 10, end at 101, and use an interval of 5
>>> x
[10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] # note that it does not hit 100
由于end
是独占的,要包括 100 个,我们可以这样做:
>>> x = range(10, 101, 5) # start at 10, end at 101, and use an interval of 5
>>> x
[10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100] # note that it does hit 100
Python 已经为这种需求内置了函数。
list = [3,8,2,9]
max_number = max(list)
print max_number # it will print 9 as big number
但是,如果您找到经典 vay 的最大数量,您可以使用循环。
list = [3,8,2,9]
current_max_number = list[0]
for number in list:
if number>current_max_number:
current_max_number = number
print current_max_number #it will display 9 as big number
student_scores[1,2,3,4,5,6,7,8,9]
max=student_scores[0]
for n in range(0,len(student_scores)):
if student_scores[n]>=max:
max=student_scores[n]
print(max)
# using for loop to go through all items in the list and assign the biggest value to a variable, which was defined as max.
min=student_scores[0]
for n in range(0,len(student_scores)):
if student_scores[n]<=min:
min=student_scores[n]
print(min)
# using for loop to go through all items in the list and assign the smallest value to a variable, which was defined as min.
注意:上面的代码是用for循环来获取最大值和最小值,其他编程语言也可以通用。但是,max() 和 min() 函数是在 Python 中使用以获得相同结果的最简单方法。
对于列表代码 HS 中的最大值,我已经设法让大部分自动分级机使用以下代码为我工作:
list = [-3,-8,-2,0]
current_max_number = list[0]
for number in list:
if number>current_max_number:
current_max_number = number
print current_max_number
def max_int_in_list():
print "Here"
我不确定 max_int_in_list 的去向。它需要恰好有 1 个参数。
打印列表中最大数字的索引。
numbers = [1,2,3,4,5,6,9]
N = 0
for num in range(len(numbers)) :
if numbers[num] > N :
N = numbers[num]
print(numbers.index(N))
我也会将此添加为参考。您可以使用排序,然后打印最后一个数字。
nums = [14, 8, 9, 16, 3, 11, 5]
nums.sort()
print("Highest number is: ", nums[-1])
scores = [12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27,
28, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 31, 31, 37,
56, 75, 23, 565]
# initialize highest to zero
highest = 0
for mark in scores:
if highest < mark:
highest = mark
print(mark)