简体   繁体   English

A Function 以“N”为参数,执行元素的增加 N 次,然后减少(N-1)次,然后作为 Python 中的列表返回

[英]A Function take 'N' as argument, performs an Increase N times of Elements then decrease (N-1) times and then return as a list in the Python

The problem is, suppose I pass 'N' = 9 to the function,问题是,假设我将'N' = 9传递给 function,

So the list will be list = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1].所以列表将是 list = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]。 At first, the list elements increased to (1-9) then it decreased to reversed order (8-1)起初,列表元素增加到(1-9)然后它减少到相反的顺序(8-1)

Please suggest the easiest way to achieve this.请提出实现这一目标的最简单方法。 Thank You in advance.先感谢您。

list(range(1, 1+N)) + list(range(N-1, 0, -1))

You can use list comprehension to achieve in one line.您可以使用列表理解在一行中实现。 First we have the list comprehension which has a simple loop that appends the number from 1 to n .首先,我们有一个列表推导式,它有一个简单的循环,将数字从 1 附加到n The second is a list comprehension where the numbers in the for loop are passed through the equation (n+1)-i .第二个是列表理解,其中 for 循环中的数字通过等式(n+1)-i传递。 This is to calculate the difference between the current value of i and n+1 .这是为了计算in+1的当前值之间的差异。 This gives us the pattern of descending numbers.这给了我们递减数字的模式。 Finally, both lists are added and stored in the variable r .最后,两个列表都被添加并存储在变量r中。

r = [x for x in range(1,n+1)] + [n+1-i for i in range(2, n+1)]

When r is printed out it produces the following output.r被打印出来时,它会产生以下 output。

[1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1]

A simple way would be to use a range from -8 to 8 and output the difference from 9 (ignoring the sign):一种简单的方法是使用从 -8 到 8 的范围和 output 与 9 的差异(忽略符号):

N = 9

print([N-abs(i) for i in range(1-N,N)])

[1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1]

the range(1-N,N) will generate: range(1-N,N)将生成:

-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8

in absolute value this will be:绝对值将是:

8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8

difference from 9与 9 的区别

9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9
8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8 -
-------------------------------------------------
1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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