python生成列表、给定一个n、删除列表中n的倍数,Python序列迭代n的倍数?

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | ming93

更新于 5 月前

一个解决方案, 尽管我敦促某人做得更好; -)

a = 'abcdef'

b = [[a[i-1], a[i]] for i in range(1, len(a), 2)]

for x, y in b:

print "%s%s\n" % (x, y)

0

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | tao78

更新于 5 月前

此解决方案提供了一系列迭代器, 每个迭代器都在

n

个元素上进行迭代。

def groupiter(thing, n):

def countiter(nextthing, thingiter, n):

yield nextthing

for _ in range(n - 1):

try:

nextitem = next(thingiter)

except StopIteration:

return

yield nextitem

thingiter = iter(thing)

while True:

try:

nextthing = next(thingiter)

except StopIteration:

return

yield countiter(nextthing, thingiter, n)

我这样使用它:

table = list(range(250))

for group in groupiter(table, 16):

print(' '.join('0x{:02X},'.format(x) for x in group))

请注意, 它可以处理的对象的长度不是

n

的倍数。

0

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | dongjun

更新于 5 月前

from __future__ import print_function # python 2.x

seq = "abcdef"

n = 2

while seq:

print("{}".format(seq[:n]), end="\n")

seq = seq[n:]

出口

ab

cd

ef

0

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | jiezhu

更新于 5 月前

那itertools呢?

from itertools import islice, groupby

def chunks_islice(seq, size):

while True:

aux = list(islice(seq, 0, size))

if not aux: break

yield "".join(aux)

def chunks_groupby(seq, size):

for k, chunk in groupby(enumerate(seq), lambda x: x[0] / size):

yield "".join([i[1] for i in chunk])

0

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | yong42

更新于 5 月前

改编自Python的

答案:

def groupsgen(seq, size):

it = iter(seq)

iterating = True

while iterating:

values = ()

try:

for n in range(size):

values += (next(it),)

except StopIteration:

iterating = False

if not len(values):

return None

yield values

它将安全地完成并且不会丢弃该值, 除非该数字可以被

size

整除。

1

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | yhe

更新于 5 月前

除了这两个答案, 我还看到很多实现包和订阅的时间过早(这并不适用于所有迭代器)。所以我想出了这个选项:

def iter_x_and_n(iterable, x, n):

yield x

try:

for _ in range(n):

yield next(iterable)

except StopIteration:

pass

def batched(iterable, n):

if n<1: raise ValueError("Can not create batches of size %d, number must be strictly positive" % n)

iterable = iter(iterable)

try:

for x in iterable:

yield iter_x_and_n(iterable, x, n-1)

except StopIteration:

pass

令我惊讶的是, 据我所知, 没有单行或多行解决方案。关键问题是外部生成器和内部生成器都必须正确处理StopIteration。如果至少保留一个元素, 则外部生成器应仅提供某些内容。一种直观的检查方法是进行下一步(...)并捕获StopIteration。

1

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | yang38

更新于 5 月前

from itertools import izip_longest

def grouper(iterable, n, fillvalue=None):

"Collect data into fixed-length chunks or blocks"

# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx

args = [iter(iterable)] * n

return izip_longest(fillvalue=fillvalue, *args)

应用:

>>> l = [1,2,3,4,5,6,7,8,9]

>>> [z for z in grouper(l, 3)]

[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

1

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | ozhu

更新于 5 月前

s = 'abcdefgh'

for e in (s[i:i+2] for i in range(0,len(s),2)):

print(e)

1

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | jing64

更新于 5 月前

more_itertools.chunked(iterable, n)

将迭代划分为给定长度的列表:

>>> list(chunked([1, 2, 3, 4, 5, 6, 7], 3))

[[1, 2, 3], [4, 5, 6], [7]]

如果迭代长度不能被n整除, 则最终返回的列表将更短。

2

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | leijing

更新于 5 月前

您可以创建以下生成器

def chunks(seq, size):

a = range(0, len(seq), size)

b = range(size, len(seq) + 1, size)

for i, j in zip(a, b):

yield seq[i:j]

并像这样使用它:

for i in chunks('abcdef', 2):

print(i)

3

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | uyao

更新于 5 月前

>>> a = "abcdef"

>>> size = 2

>>> [a[x:x+size] for x in range(0, len(a), size)]

['ab', 'cd', 'ef']

..或不作为列表理解:

a = "abcdef"

size = 2

output = []

for x in range(0, len(a), size):

output.append(a[x:x+size])

或作为多次使用的最佳生成器(对于一次使用, 列表理解可能是最佳):

def chunker(thelist, segsize):

for x in range(0, len(thelist), segsize):

yield thelist[x:x+segsize]

..及其用途:

>>> for seg in chunker(a, 2):

... print seg

...

ab

cd

ef

4

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | udeng

更新于 5 月前

并且总是有

文档。

def pairwise(iterable):

"s -> (s0,s1), (s1,s2), (s2, s3), ..."

a, b = tee(iterable)

try:

b.next()

except StopIteration:

pass

return izip(a, b)

def grouper(n, iterable, padvalue=None):

"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"

return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)

注意: 如果使用字符串序列作为输入, 它们将创建元组而不是子字符串。

6

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | taosu

更新于 5 月前

但是, 更通用的方法是(的答案受到

的启发):

for i in zip(*(seq[i::size] for i in range(size))):

print(i) # tuple of individual values

6

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | yang57

更新于 5 月前

不要忘记zip()函数:

a = 'abcdef'

for x,y in zip(a[::2], a[1::2]):

print '%s%s' % (x,y)

12

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | xlu

更新于 5 月前

我还有另一种方法, 用于未知长度的迭代。

def groupsgen(seq, size):

it = iter(seq)

while True:

values = ()

for n in xrange(size):

values += (it.next(),)

yield values

它的工作方式是按大小迭代一组序列(或其他迭代器), 然后将值收集到一个元组中。在每个组的末尾, 它返回一个元组。

当迭代器的值用完时, 它将引发StopIteration异常, 然后该异常向上传播, 表明groupsgen中没有任何值。

假定该值是一组尺寸(一组2. 3等)。如果不是, 则将所有剩余值简单地丢弃。

15

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | yongcheng

更新于 5 月前

生成器功能非常简洁:

def batch_gen(data, batch_size):

for i in range(0, len(data), batch_size):

yield data[i:i+batch_size]

用法示例:

a = "abcdef"

for i in batch_gen(a, 2): print i

印刷品:

ab

cd

ef

47

0

c9fc01ef3696a1a5eb806a570674c46b.png

作者 | xiulan39

更新于 5 月前

我确定有人会建议更多Pythonic, 但如何:

for y in range(0, len(x), 2):

print "%s%s" % (x[y], x[y+1])

请注意, 只有您知道

len(x) % 2 == 0;

10

0

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值