mylist1=[11,4,5,6,8,6,3]
for i in mylist1:
a=list(range(i))
print(a)
print (a[-2:2])
我知道(a[-2:2])是错的,但是我可以用a[0:4]做点什么。我希望结果是:
输入列表的列表:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5]
[0, 1, 2]
:
[ 9, 10, 0, 1]
[2, 3, 0, 1]
[3, 4, 0, 1, ]
[4, 5, 0, 1 ]
[6, 7, 0, 1,]
[4, 5, 0, 1, ]
[1, 2, 0, 1]
例如,我想这样写:
[a[-2],a[-1],a[0],a[1],a[2]]
但是它很笨拙。有什么干净利落的方法吗?
另一种方法是:
mylist1 = [11, 4, 5, 6, 8, 6, 3]
for i in mylist1:
a = list(range(i))
print(a[-2:] + a[:2])
[9, 10, 0, 1]
[2, 3, 0, 1]
[3, 4, 0, 1]
[4, 5, 0, 1]
[6, 7, 0, 1]
[4, 5, 0, 1]
[1, 2, 0, 1]
你可以尝试这样做:
list1 = [0, 1, 2, 3, 4, 5]
for ln in range(1, len(list1)):
list2 = [list1[n] for n in range(-ln, ln)] #magic line
print(list2)
或者你也可以试着用下面这行来代替:
list2 = list1[ln:] + list1[:ln]
其中ln
是列表开始和结束的元素个数。
也可以使用列表推导式
mylist1 = [11,4,5,6,8,6,3]
# [range(i) for i in mylist1] creates an array of ranges based on mylist
# [a[j] for j in range(-2,2)] for a in ... selects elements
# a[-2],a[-1],a[0],a[1] if you need a[2] then
# change range(-2,2) to range(-2,3)
mylist2 = [[a[j] for j in range(-2,2)] for a in [range(i) for i in mylist1]]