【问题标题】:Python: how to create sublists through loop?Python:如何通过循环创建子列表?
【发布时间】:2016-10-12 20:23:59
【问题描述】:

我有一个很长的列表,其中包含值从 0 到 100 的元素。 我想要做的是找到我的元素取值 [0,2] 的所有位置。然后找出 2 和 4 之间的值的所有位置,以此类推,直到 98 和 100。

让我们将包含值的列表称为“列表”。我们称结果列表为 p_x。其中 x 表示我们正在寻找哪个区间的位置。

我设法通过这种方式得到了我想要的东西: p_61 = N.where((list >= 60) & (list

我现在的问题是:我如何循环这个,以便得到我想要的所有 p_x?

【问题讨论】:

  • 这是 Numpy 的吗? (因为你用where
  • 是的,我用过 numpy。

标签: python list loops


【解决方案1】:
import itertools

l = list(range(10))

## If you just want the values:
print([(x,y) for (x,y) in itertools.combinations(l, 2) if abs(x-y)==2])

## If you want the positions:
for i, x in enumerate(l):
    for j, y in enumerate(l):
        if j <= i:
            continue
        if abs(x-y) == 2:
            print(i, j)

## If you want them stored in lists in a dictionary:
d = {}
for i, x in enumerate(l):
    for j, y in enumerate(l):
        if j <= i:
            continue
        if abs(x-y) == 2:
            k = 'p_{}'.format(x+1)
            try:
                d[k].append((i,j))
            except KeyError:
                d[k] = [(i,j)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 2019-08-16
    • 2019-12-20
    • 2022-08-10
    • 2021-06-08
    相关资源
    最近更新 更多