简体   繁体   English

如何将 dict 值中的列表元素提高到 x 的幂?

[英]How do I raise list element in dict value to power of x?

I am a beginner in Python and have several exercises to resolve.我是Python的初学者,有几个习题要解决。

One of these is:其中之一是:

"Define a dictionary w/ keys "abc", "xyz" and values [1, 2, 3] and [9, 10, 11]; iterate over all values (lists) and raise to the power of 4 each element of each list and print to screen" “定义一个带有键“abc”、“xyz”和值 [1、2、3] 和 [9、10、11] 的字典;遍历所有值(列表)并计算每个元素的 4 次方列出并打印到屏幕”

...and I am bit lost. ......我有点迷路了。 I could define a function that raises the power of each element in a list, but I do not know how to do it in a dictionary:(我可以定义一个 function 来提高列表中每个元素的能力,但我不知道如何在字典中做到这一点:(

This is where I am stuck:这就是我被困的地方:

dex = {"abc":[1,2,3],"xyz":[9,10,11]}
for x in dex.values():
     print(x)

Since it's nested you could use a loop in a loop to get each item of each list, like this:由于它是嵌套的,您可以在循环中使用循环来获取每个列表的每个项目,如下所示:

dex = {"abc":[1,2,3],"xyz":[9,10,11]}
for x in dex.values():
     for el in x:
         print(el**4)

or using dict and list comprehension:或使用字典和列表理解:

dex = {"abc":[1,2,3],"xyz":[9,10,11]}
dex = {k: [el**4 for el in v] for k, v in dex.items()}
print(dex)

This way should work, if you can use dict comprehensions.如果您可以使用字典理解,这种方式应该有效。 It uses map , which applies a function to each elem in a list.它使用map ,它将 function 应用于列表中的每个元素。

my_dict = {"abc": [1, 2, 3], "xyz": [9, 10, 11]}
new_dict = {key: list(map(lambda x: x ** 4, val)) for key, val in my_dict.items()}

Here, we map a function that raises each item in the list to a power.在这里,我们 map 和 function 将列表中的每个项目提升为幂。

Depending on how you want to present the output, this might work for you:根据您想要呈现 output 的方式,这可能适合您:

dex = {"abc": [1,2,3], "xyz": [9,10,11]}
print([[e**4 for e in lst] for lst in dex.values()])

Output: Output:

[[1, 16, 81], [6561, 10000, 14641]]

This should work:这应该工作:

dex = {"abc":[1,2,3],"xyz":[9,10,11]}

def print_exp (dic) :
    for i,j in dic.items() :
        if isinstance(j,list):
            for n in j :
                print(n**4)
            
print_exp(dex)

This one is with a function definition.这是一个 function 定义。

Without function definition you can achieve this by:如果没有 function 定义,您可以通过以下方式实现:

dex = {"abc":[1,2,3],"xyz":[9,10,11]}


for i,j in dex.items() :
    if isinstance(j,list):
        for n in j :
            print(n**4)
            

Since the index (or the power) stays constant, the magic method __rpow__ can be used to chain the operations: a**4 <--> int.__pow__(a, 4) <--> int.__rpow__(4, a)由于索引(或幂)保持不变,魔术方法__rpow__可用于链接操作: a**4 <--> int.__pow__(a, 4) <--> int.__rpow__(4, a)

dex = {"abc":[1,2,3],"xyz":[9,10,11]}

pows = [list(map(int(4).__rpow__, l)) for l in dex.values()]

print(pows)

Output Output

[[1, 16, 81], [6561, 10000, 14641]]

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

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