如何在字典的子集上进行迭代?

发布于 2025-01-25 14:48:54 字数 593 浏览 4 评论 0原文

我是编码的新手,但是我有一个现实生活中的问题,我想拥有一些代码。我有一个项目列表,每个项目都有位置 - 我将其放入python中,例如objects = {“ a”:0,“ B”:7,“ C”:24,“ D”:2}

如何循环浏览此词典并找到每对项目的中点?我缩写为“ x/y”。因此,最终我想要看起来像Midpoints = {“ A/B”:3.5,“ A/C”:12,“ A/D”:1,“ B/C”:15.5,“ B/ D“:4.5,” C/D“:13}

我知道您将从函数和一个循环开始,也许是类似的东西

def mp(x,y):
    return (x+y)/2

midpoints = {}

for key1 in objects:
    for key2 in objects:
        midpoints[key1+"/"+key2] = mp(objects[key1],objects[key2])

,但是这给出了无用的中点(“ a/a”)以及重复的中点(例如“ a/b”和“ b/a”) 。

我不知道如何清理……我想您必须在字典的一部分上迭代?任何帮助将不胜感激! :)

I am very new to coding, but I have a real-life problem that I want to have some code for. I have a list of items, which each have locations - I put it into Python as something like objects = {"a": 0, "b": 7, "c": 24, "d": 2}

How do I loop through this dictionary and find the midpoints of each pair of items? I abbreviate midpoint as "x/y". So ultimately I want something that looks like, midpoints = {"a/b": 3.5, "a/c": 12, "a/d": 1, "b/c": 15.5, "b/d": 4.5, "c/d": 13}.

I know you'd start with a function and a for loop, maybe something like

def mp(x,y):
    return (x+y)/2

midpoints = {}

for key1 in objects:
    for key2 in objects:
        midpoints[key1+"/"+key2] = mp(objects[key1],objects[key2])

but this is giving useless midpoints ("a/a") as well as repeated midpoints (e.g. both "a/b" and "b/a").

I can't figure out how to clean this up...I guess you'd have to iterate over a subset of the dictionary? Any help would be greatly appreciated! :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

为人所爱 2025-02-01 14:48:54

您正在寻找A 笛卡尔产品。您的实现几乎是正确的,但是中点[key1+“/”+key2] = z行需要缩进为每对(key1,key2)运行。

def mp(x,y):
    return (x+y)/2

midpoints = {}

for key1 in objects:
    for key2 in objects:
        z = mp(objects[key1],objects[key2])
        midpoints[key1+"/"+key2] = z

如果您现在打印(中点),您将获得{'a/a':0.0,'a/b':3.5,'a/c':12.0,'a/a/ D':1.0,'b/a':3.5,'b/b':7.0,'b/c':15.5,'b/d':4.5,'c/a':12.0,'c/b' :15.5,'c/c':24.0,'c/d':13.0,'d/a':1.0,'d/b':4.5,'d/c':13.0,'d/d':2.0 }。从您的示例中,我推断您要简化这一点:

  • X/X不应出现在最终字典中;
  • X/Yy/x只能以一种

实现此目的的一种方法出现一个是需要key1< key2(词汇比较):

for key1 in objects:
    for key2 in objects:
        if key1 < key2:
            z = mp(objects[key1],objects[key2])
            midpoints[key1+"/"+key2] = z

这与您的示例相似。如果要包括X/X,只需更改key1&lt; key2 to key1&lt; = key2

You're looking for a cartesian product. Your implementation is almost correct, but the midpoints[key1+"/"+key2] = z line needs to be indented to run for every pair (key1, key2).

def mp(x,y):
    return (x+y)/2

midpoints = {}

for key1 in objects:
    for key2 in objects:
        z = mp(objects[key1],objects[key2])
        midpoints[key1+"/"+key2] = z

if you now print(midpoints), you'll obtain {'a/a': 0.0, 'a/b': 3.5, 'a/c': 12.0, 'a/d': 1.0, 'b/a': 3.5, 'b/b': 7.0, 'b/c': 15.5, 'b/d': 4.5, 'c/a': 12.0, 'c/b': 15.5, 'c/c': 24.0, 'c/d': 13.0, 'd/a': 1.0, 'd/b': 4.5, 'd/c': 13.0, 'd/d': 2.0}. From your example I infer that you want to simplify this:

  • x/x should not appear in the final dictionary;
  • only one of x/y and y/x should appear in the dict

one way to achieve this would be to require key1 < key2 (lexical comparison):

for key1 in objects:
    for key2 in objects:
        if key1 < key2:
            z = mp(objects[key1],objects[key2])
            midpoints[key1+"/"+key2] = z

this yields a dict similar to the one from your example. If you want to include x/x, just change key1 < key2 to key1 <= key2.

您可以使用 itertools.combinationss.combinations

from itertools import combinations

objects = {"a": 0, "b": 7, "c": 24, "d": 2}


def mp(x, y):
    return (x + y) / 2


midpoints = {
    f"{x}/{y}": mp(objects[x], objects[y]) for x, y in combinations(objects, 2)
}
print(midpoints)

打印:

{"a/b": 3.5, "a/c": 12.0, "a/d": 1.0, "b/c": 15.5, "b/d": 4.5, "c/d": 13.0}

You can use itertools.combinations:

from itertools import combinations

objects = {"a": 0, "b": 7, "c": 24, "d": 2}


def mp(x, y):
    return (x + y) / 2


midpoints = {
    f"{x}/{y}": mp(objects[x], objects[y]) for x, y in combinations(objects, 2)
}
print(midpoints)

Prints:

{"a/b": 3.5, "a/c": 12.0, "a/d": 1.0, "b/c": 15.5, "b/d": 4.5, "c/d": 13.0}
も让我眼熟你 2025-02-01 14:48:54

要避免重复项,请使用枚举获得索引,然后通过内部环中的对象的切片列表进行迭代:

midpoints = {}
items = list(objects.items())   # convert to a list so we can slice it
for i, (key_a, a) in enumerate(items[:-1]):
    for key_b, b in items[i + 1:]:  # takes the remaining items (index > i)
        midpoints[f"{key_a}/{key_b}"] = (a + b) / 2

或者使用 itertools.combinations ,它在不重复的情况下生成了所有峰值的组合:

from itertools import combinations
midpoints = {}
for (key_a, a), (key_b, b) in combinations(objects.items(), 2):
    midpoints[f"{key_a}/{key_b}"] = (a + b) / 2

To avoid duplicates, use enumerate to obtain an index, and iterate through a sliced list of the objects in the inside loop:

midpoints = {}
items = list(objects.items())   # convert to a list so we can slice it
for i, (key_a, a) in enumerate(items[:-1]):
    for key_b, b in items[i + 1:]:  # takes the remaining items (index > i)
        midpoints[f"{key_a}/{key_b}"] = (a + b) / 2

Alternatively use itertools.combinations which generates all combinations of an iterable without repetition:

from itertools import combinations
midpoints = {}
for (key_a, a), (key_b, b) in combinations(objects.items(), 2):
    midpoints[f"{key_a}/{key_b}"] = (a + b) / 2
信仰 2025-02-01 14:48:54

您也许可以尝试以下类似的东西。逻辑是将嵌套的循环用于两个点,然后使用IF条件仅在Numerator和分母为不同点的情况下添加值。

objects = {"a": 0, "b": 7, "c": 24, "d": 2}
midpoints = {}
for num in objects:
    for denom in objects:
        if num != denom:
            midpoints[f'{num}/{denom}'] = (objects[num] + objects[denom]) / 2
            
print(midpoints)

You can perhaps try something like the below. The logic is to use a nested for loop for the two points, then use an if condition to only add in the value if numerator and denominator would be different points.

objects = {"a": 0, "b": 7, "c": 24, "d": 2}
midpoints = {}
for num in objects:
    for denom in objects:
        if num != denom:
            midpoints[f'{num}/{denom}'] = (objects[num] + objects[denom]) / 2
            
print(midpoints)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文