简体   繁体   English

字典中键值对中的值变量

[英]Variable in value in key-value pairs in dictionaries

Let's say we have dictionary = ['a':x*2,'b':x*3] , and we set x to 2. When I print out the dictionary after this assignment, I get the one shown above, and not ['a':4,'b':6] .假设我们有dictionary = ['a':x*2,'b':x*3] ,我们将x设置为 2。当我在分配后打印出字典时,我得到了上面显示的那个,而不是['a':4,'b':6] Why is that?这是为什么? I am currently trying to come up with a solution to Project Euler exercise 69 ( https://projecteuler.net/problem=69 ) for which I have made the following:我目前正在尝试为 Project Euler 练习 69 ( https://projecteuler.net/problem=69 ) 提出解决方案,为此我做了以下工作:

import math

from sympy import Symbol

magic_book={1:1,2:1}

maximum=0

for n in range(3,10**6+1):

    print(magic_book)
    print(n)
    if n in magic_book:
        if (n/magic_book[n])>maximum:
            maximum=n/magic_book[n]
        continue
        
    Phi=0
    x = Symbol('x')
    
    for m in range(1,n):
        if math.gcd(n,m)==1:
            magic_book[n*m]=x*magic_book[m]
            Phi+=1
    x=Phi
    if n/Phi>maximum:
        maximum=n/Phi
    
print(maximum)

When I set x equal Phi , magic_book does not update - why is this?当我设置x等于Phi时, magic_book不会更新 - 这是为什么?

When you edit an object in Python, it does not go back and change what you previously stated using it.当您在 Python 中编辑 object 时,它不会返回 go 并更改您之前使用它声明的内容。 See for example:参见例如:

x = 1
double_x = 2*x
x = 10

Your question is basically asking why double_x is not 20.你的问题基本上是问为什么double_x不是 20。

In order to substitute symbolic values with other values (like numeric values), .subs() is usually the best option if you are dealing with SymPy objects.为了用其他值(如数值)替换符号值,如果您正在处理 SymPy 对象, .subs()通常是最佳选择。 However, a dictionary is not a SymPy object and it does not have a .subs() method.但是,字典不是 SymPy object 并且它没有.subs()方法。 You must then loop through the dictionary and substitute its values like so:然后,您必须遍历字典并替换它的值,如下所示:

for k, v in magic_book.items():
    maximum[k] = v.subs(x, Phi)  # assuming v is a SymPy object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM