简体   繁体   中英

Creating a general list of ascending and descending numbers using list comprehension

I am trying to generate a list containing a mixture of ascending and descending numbers.

eg, say you have n=5 . I want to generate a list/array based on n such that you have:

[0,1,2,3,4,3,2,1,0]

using list comprehension.

I tried doing this:

print [[i+j] for i in range(n)for j in range(n,-1,-1)]

but I can't seem to get it right.

I know you specified you wanted a list comp, but is it really necessary?

list(range(5)) + list(reversed(range(4)))

(python 3 syntax)

Or, in python2:

range(5) + range(4)[::-1]

or

range(5) + range(3,-1,-1)

I think the first one is more readable, but ymmv.

In [27]: n = 5

In [28]: [n-1-abs(i-n+1) for i in range(n*2-1)]
Out[28]: [0, 1, 2, 3, 4, 3, 2, 1, 0]

Update

This one might be more clear

In [36]: [n-abs(i) for i in range(-n,n+1)]
Out[36]: [0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]

One-liner:

[i if i < n else 2*(n-1)-i for i in range(2*(n-1) + 1)]

More efficient:

_top = 2*(n-1)
[i if i < n else _top-i for i in range(_top + 1)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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