所以我有这个列表和变量:
nums = [14, 8, 9, 16, 3, 11, 5]
big = nums[0]
spot = 0
我对如何实际操作感到困惑。请帮忙!我是Python新手,我想用这个练习给我一个启动器。我想从Scratch或BYOB中的“重复列表长度”开始,但是我如何在Python上做到这一点?
答案 0 :(得分:13)
通常,你可以使用
max(nums)
如果您明确要使用循环,请尝试:
max_value = None
for n in nums:
if n > max_value: max_value = n
答案 1 :(得分:9)
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
答案 2 :(得分:8)
你去......
nums = [14, 8, 9, 16, 3, 11, 5]
big = max(nums)
spot = nums.index(big)
这将是Pythonic实现这一目标的方式。如果要使用循环,则使用当前最大值循环并检查每个元素是否更大,如果是,则分配给当前最大值。
答案 3 :(得分:1)
答案 4 :(得分:1)
要解决第二个问题,您可以使用for
循环:
for i in range(len(list)):
# do whatever
您应该注意range()
可以包含3个参数:start
,end
和step
。 Start是开头的数字(如果没有提供,则为0);开始是包容的..结束是在哪里结束(这必须给予);结束是独家的:如果你做range(100)
,它会给你0-99。步骤也是可选的,它表示使用的间隔。如果未提供步骤,则为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
答案 5 :(得分:0)
Python已经内置了这种要求的功能。
list = [3,8,2,9]
max_number = max(list)
print max_number # it will print 9 as big number
但是如果你找到经典视频的最大数字,你可以使用循环。
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
答案 6 :(得分:0)
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)
答案 7 :(得分:0)
对于Max in List Code 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个参数。
答案 8 :(得分:0)
要打印列表中编号最大的索引。
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))
答案 9 :(得分:0)
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中获得相同结果的最简单方法。