根据输入切片大列表

时间:2019-02-23 01:12:28

标签: python list slice

如果我有多个这样的列表

hello = [1,3,5,7,9,11,13]

bye = [2,4,6,8,10,12,14]

,用户输入3

有没有一种方法可以使输出返回列表中的3个索引并从那里开始获取:

9 10

11 12 

13 14

在每个空格之间带有制表符\t

如果用户输入5

预期输出为

5 6

7 8

9 10

11 12

13 14

我尝试过

for i in range(user_input):
    print(hello[-i-1], '\t', bye[-i-1])

6 个答案:

答案 0 :(得分:3)

只需使用从末尾减去用户输入(-user_input)到末尾(-1)的负索引,就像这样:

for i in range(-user_input, 0):
    print(hello[i], bye[i])

答案 1 :(得分:0)

在切片中使用负索引。

hello = [1,3,5,7,9,11,13]

print(hello[-3:])

print(hello[-3:-2])

输出

[9, 11, 13]
[9]

答案 2 :(得分:0)

您可以zip这两个列表,并使用itertools.islice获得输出的所需部分:

from itertools import islice
print('\n'.join(map(' '.join, islice(zip(map(str, hello), map(str, bye)), len(hello) - int(input()), len(hello)))))

给出3的输入,将输出:

5 6
7 8
9 10
11 12
13 14

答案 3 :(得分:0)

您可以使用zip返回一个元组列表,其中第i个元素来自第i个可迭代参数。

zip_ = list(zip(hello, bye))
for item in zip_[-user_input:]:
    print(item[0], '\t' ,item[1])

然后使用负索引获取您想要的内容。

答案 4 :(得分:0)

另一种zip解决方案,但只有一行:

for h, b in zip(hello[-user_input:], bye[-user_input:]):
    print(h, b, sep='\t')

避免将zip的结果转换为list,因此唯一的临时对象是hellobye的切片。尽管通过索引进行迭代可以避免这些临时操作,但实际上,进行切片和迭代值通常总是更干净,更快速,因为在CPython中重复索引既不合python且出奇地慢。

答案 5 :(得分:0)

如果要分析数据

我认为使用 pandas.datafrme 可能会有所帮助。

INPUT_INDEX = int(input('index='))

df = pd.DataFrame([hello, bye])
df = df.iloc[:, len(df.columns)-INPUT_INDEX:]
for col in df.columns:
    h_value, b_value = df[col].values
    print(h_value, b_value)

控制台

index=3
9 10
11 12
13 14
相关问题