根据输入切割大型列表

问题描述 投票:3回答:6

如果我有多个这样的列表

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])
python list slice
6个回答
3
投票

只需使用从结尾开始的负索引减去用户输入(qazxsw poi)并移动到结尾(qazxsw poi),例如:

-user_input

0
投票

在切片中使用否定索引。

-1

产量

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

0
投票

您可以hello = [1,3,5,7,9,11,13] print(hello[-3:]) print(hello[-3:-2]) 这两个列表并使用[9, 11, 13] [9] 来获得所需的输出部分:

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)))))

0
投票

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

5 6
7 8
9 10
11 12
13 14

然后使用负面索引来获得你想要的东西。


0
投票

另一个zip解决方案,但一线:

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

避免将zip的结果转换为for h, b in zip(hello[-user_input:], bye[-user_input:]): print(h, b, sep='\t') ,因此唯一的临时工具是ziplist的切片。虽然通过索引进行迭代可以避免那些临时性,但实际上,切片和迭代值几乎总是更清晰,更快,因为重复索引在CPython中既是单声道的,也是令人惊讶的慢。


0
投票

如果要分析数据

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

hello

安慰

bye
© www.soinside.com 2019 - 2024. All rights reserved.