[英]How to repeat the largest element in a list by the length of the list
Write a Python function called all_change_to_max_end that takes as input a list of integers, determines which is larger, the first or last element in the list, and then sets all the other elements to be that value.编写一个名为 all_change_to_max_end 的 Python function 将整数列表作为输入,确定列表中的第一个或最后一个元素哪个更大,然后将所有其他元素设置为该值。 Output the changed list.
Output 更改列表。
Sample inputs and output:示例输入和 output:
all_change_to_max_end([1, 2, 4, 9, 3]) # should be [3, 3, 3, 3, 3]
all_change_to_max_end([11, 5, 9]) # should be [11, 11, 11]
all_change_to_max_end([2, 11]) # should be [11, 11]
I've tried using:我试过使用:
def all_change_to_max_end(a_list):
return max(a_list) * len(a_list)
but this does not work as it multiples the largest number by the total length但这不起作用,因为它将最大数字乘以总长度
all_change_to_max_end([2, 10, 4, 8]
40
Any help would be greatly appreciated!任何帮助将不胜感激!
You need to check the max of these two elements (first and last)您需要检查这两个元素的最大值(第一个和最后一个)
def all_change_to_max_end(a_list):
return [max(a_list[0], a_list[-1])] * len(a_list)
The correct answer is: [max(a_list[-1], a_list[0])] * len(a_list)
.正确答案是:
[max(a_list[-1], a_list[0])] * len(a_list)
。
Pass a list in this function:在此 function 中传递一个列表:
def all_change_to_max_end(x):
#select maximum and converting it to list
return [max(x[0], x[-1])]*(len(x))
numbers = [1, 5, 8, 4, 3, 7, 9, 7]
print(all_change_to_max_end(numbers))
Out[79]: [7, 7, 7, 7, 7, 7, 7, 7]
出 [79]: [7, 7, 7, 7, 7, 7, 7, 7]
Do this change做这个改变
When you do max(list) it returns a value not a list so multiplying it to a number is simple multiplication.当您执行 max(list) 时,它返回一个值而不是列表,因此将其乘以一个数字是简单的乘法。
max(list) * len(list) #let max = 10 and length = 4, then its output is 40
so do也一样
[max(list[0],list[-1])]
This is sample output这是样品 output
>>> a = [1, 2, 4, 9, 3]
>>> def all_change_to_max_end(a_list):
... return [max(a_list[0],a_list[-1])] * len(a_list)
...
>>> all_change_to_max_end(a)
[3, 3, 3, 3, 3]
you can do:你可以做:
def all_change_to_max_end(l):
a = l[0]
b = l[-1]
return [max(a,b)] * len(l)
print(all_change_to_max_end([11, 5, 9]))
output output
[11, 11, 11]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.