gpt4 book ai didi

python:两个配对列表的索引/分页

转载 作者:太空宇宙 更新时间:2023-11-04 10:22:38 31 4
gpt4 key购买 nike

假设我有两个这样的列表,它们必须成对表示:

cities = ['San Francisco', 'New York', 'Seattle', 'Portland', ]
states = ['CA', 'NY', 'WA', 'OR']

我有一个这样的函数:

def list(page):
return "{0} -> {1} \n {2} -> {3} \n {4} -> {5} \n {6} -> {7}".format(keys[0], values[0], keys[1], values[1], keys[2], values[2], keys[3], values[3])

我希望能够使用一个整数(此处为 page)来索引这些对,一次显示三个。假设我有十对城市和州,1 它将显示前三个,2 后三个,等等。

伪装的,我想它看起来像这样:

def list(page):
for page < 2:
return first triplet
for page < 3:
return second triplet
# etc.

但我认为可能有更好的方法,我想知道它会是什么样子。

最佳答案

设置:

cities = ['San Francisco', 'New York', 'Seattle', 'Portland', ]
states = ['CA', 'NY', 'WA', 'OR']

A function to split a generator into chunks :

from itertools import islice

def chunks(iterable, size=10):
iterator = iter(iterable)
for first in iterator: # stops when iterator is depleted
def chunk(): # construct generator for next chunk
yield first # yield element from for loop
for more in islice(iterator, size - 1):
yield more # yield more elements from the iterator
yield chunk() # in outer generator, yield next chunk

这为您提供了一个生成给定大小块的生成器。放在一起:

>>> for chunk in chunks(zip(cities, states)):
... for piece in chunk:
... print('{}, {}'.format(*piece))
...
San Francisco, CA
New York, NY
Seattle, WA
Portland, OR

你也可以把它变成一个 list block ,如下所示:

>>> places = [list(chunk) for chunk in chunks(zip(cities, states), 3)]
>>> places[0]
[('San Francisco', 'CA'), ('New York', 'NY'), ('Seattle', 'WA')]

并打印给定的 block :

>>> print(*('{}, {}'.format(*place) for place in places[0]), sep='\n')
San Francisco, CA
New York, NY
Seattle, WA

关于python:两个配对列表的索引/分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31419666/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com