从整数列表中获取三的倍数的值在Python中。

huangapple go评论87阅读模式
英文:

Getting values in multiples of three from list of integers in python

问题

I'm looking for a way to get 3 values from a list at a time. Let's say I have a list of dimensions for x items: packages = [length, width, height, length, width, height,...] and I want to get the l, w , and h for each item separately. Anyone know of a way to do this? I do know the value of x if that makes any difference.

The following was in the code I used but it doesn't seem to work:

packages = [2400, 1000, 800, 2400, 1000, 1000, 2400, 1000, 1000]
for each in packages:
        l, w, h = each[3:]
英文:

I'm looking for a way to get 3 values from a list at a time. Let's say I have a list of dimensions for x items: packages = [length, width, height, length, width, height,...] and I want to get the l, w , and h for each item separately. Anyone know of a way to do this? I do know the value of x if that makes any difference.

The following was in the code I used but it doesn't seem to work:

packages = [2400, 1000, 800, 2400, 1000, 1000, 2400, 1000, 1000]
for each in packages:
        l, w, h = each[3:]

答案1

得分: 2

你可以在每隔3个元素处对列表进行切片。

packages = [2400, 1000, 800, 2400, 1000, 1000, 2400, 1000, 1000]
packages = [packages[x:x+3] for x in range(0, len(packages), 3)]
print(packages)

输出结果为

[[2400, 1000, 800], [2400, 1000, 1000], [2400, 1000, 1000]]
英文:

You can slice the list at gaps of 3.

packages = [2400, 1000, 800, 2400, 1000, 1000, 2400, 1000, 1000]
packages = [packages[x:x+3] for x in range(0, len(packages), 3)]
print(packages)

Output is

[[2400, 1000, 800], [2400, 1000, 1000], [2400, 1000, 1000]]

答案2

得分: 1

你可以使用“zip迭代器自身”技巧:

i = iter(packages)
for l, w, h in zip(i, i, i):
    # 做不可言喻的事情

或者对于通用的块大小 n

for chunk in zip(*(i for _ in range(n))):
英文:

You can use the "zip iterator with itself" trick:

i = iter(packages)
for l, w, h in zip(i, i, i):
    # do unspeakable things

Or for generic chunk sizes ``n:

for chunk in zip(*(i for _ in range(n))):

答案3

得分: 1

如果您知道列表的长度将为 length % n == 0,那么您可以使用名为 batched 的itertools示例来进行批处理:

def batched(iterable, n):
    "将数据批处理成长度为n的元组。最后一个批次可能较短。"
    # batched('ABCDEFG', 3) --> ABC DEF G
    if n < 1:
        raise ValueError('n必须至少为1')
    it = iter(iterable)
    while batch := tuple(islice(it, n)):
        yield batch

在使用中:

packages = [2400, 1000, 800, 2400, 1000, 1000, 2400, 1000, 1000]
for l, w, h in batched(packages, 3):
    ...

如果您想要更多关于长度不满足 length % n == 0 的可迭代对象的选项,您可以使用 grouper 示例:

def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
    "将数据收集到非重叠的固定长度块或块中"
    # grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
    # grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
    # grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
    args = [iter(iterable)] * n
    if incomplete == 'fill':
        return zip_longest(*args, fillvalue=fillvalue)
    if incomplete == 'strict':
        return zip(*args, strict=True)
    if incomplete == 'ignore':
        return zip(*args)
    else:
        raise ValueError('预期的选项为fill、strict或ignore')

最后如果不使用itertools但有点巧妙),可以使用来自[此答案](https://stackoverflow.com/a/54374626/225020)的代码

```python
d = iter(i)
for l, w, h in zip(*[d]*3):
    ...

请注意,以上内容是代码示例的翻译部分,不包括问题或其他内容。

英文:

If you know the list will be of length % n == 0 thenyou can use the itertools recipe called batched

def batched(iterable, n):
    &quot;Batch data into tuples of length n. The last batch may be shorter.&quot;
    # batched(&#39;ABCDEFG&#39;, 3) --&gt; ABC DEF G
    if n &lt; 1:
        raise ValueError(&#39;n must be at least one&#39;)
    it = iter(iterable)
    while batch := tuple(islice(it, n)):
        yield batch

In use:

packages = [2400, 1000, 800, 2400, 1000, 1000, 2400, 1000, 1000]
for l, w, h in batched(packages, 3):
    ...

And if you want more options as far as iterables that do not have length % n == 0 length then you can use the grouper recipe:

def grouper(iterable, n, *, incomplete=&#39;fill&#39;, fillvalue=None):
    &quot;Collect data into non-overlapping fixed-length chunks or blocks&quot;
    # grouper(&#39;ABCDEFG&#39;, 3, fillvalue=&#39;x&#39;) --&gt; ABC DEF Gxx
    # grouper(&#39;ABCDEFG&#39;, 3, incomplete=&#39;strict&#39;) --&gt; ABC DEF ValueError
    # grouper(&#39;ABCDEFG&#39;, 3, incomplete=&#39;ignore&#39;) --&gt; ABC DEF
    args = [iter(iterable)] * n
    if incomplete == &#39;fill&#39;:
        return zip_longest(*args, fillvalue=fillvalue)
    if incomplete == &#39;strict&#39;:
        return zip(*args, strict=True)
    if incomplete == &#39;ignore&#39;:
        return zip(*args)
    else:
        raise ValueError(&#39;Expected fill, strict, or ignore&#39;)

Finally, without using itertools, (but it's a bit hacky) from this answer:

d = iter(i)
for l, w, h in zip(*[d]*3):
    ...

huangapple
  • 本文由 发表于 2023年6月27日 20:25:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定