Py学习  »  Python

python—从函数调用中去掉括号?

Landon G • 4 年前 • 700 次点击  

我正在编写一个接受1个参数的函数,我希望该参数是一个列表。 我基本上已经得到了我想要的所有行为,除了或一件事:`

def index_responses(a):
    j = {}
    count = 0
    key = 0
    for y in a:
       j["Q",key]=a[count]
       count+=1
       key+=1
    print(j)
    return a

以下是函数调用:

print(index_responses(['a', 'b', 'c']))
print(index_responses(['d','d','b','e','e','e','d','a']))

我的输出是:

{('Q', 0): 'a', ('Q', 1): 'b', ('Q', 2): 'c'}
{('Q', 0): 'd', ('Q', 1): 'd', ('Q', 2): 'b', ('Q', 3): 'e', ('Q', 4): 'e', ('Q', 5): 'e', ('Q', 6): 'd', ('Q', 7): 'a'}

但我需要我的输出看起来更干净,更像: (Q1:'A',Q2:'B'(等…)

如何清理输出?

谢谢你的回复。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38261
 
700 次点击  
文章 [ 2 ]  |  最新文章 4 年前
Prune
Reply   •   1 楼
Prune    5 年前

认为 只需将“q”连接到 key :

   j["Q" + str(key)]=a[count]

这个变化给出了输出

{'Q0': 'a', 'Q1': 'b', 'Q2': 'c'}
['a', 'b', 'c']
{'Q0': 'd', 'Q5': 'e', 'Q6': 'd', 'Q7': 'a', 'Q1': 'd', 'Q3': 'e', 'Q4': 'e', 'Q2': 'b'}
['d', 'd', 'b', 'e', 'e', 'e', 'd', 'a']

有更好的方法来计算列表中的项目;我将把这些留给您的研究。

Austin
Reply   •   2 楼
Austin    5 年前

使用 "Q" + str(key) f"Q{str(key)}" (在python 3.6+上)在循环中:

def index_responses(a):
    j = {}
    count = 0
    key = 1
    for y in a:
       j["Q" + str(key)] = a[count]
       count += 1
       key += 1
    return j

print(index_responses(['a', 'b', 'c']))
print(index_responses(['d','d','b','e','e','e','d','a']))

同时请注意,您需要返回 j 而不是 a 它实际上是函数的输入。


获得相同结果的一种更为清洁、更为蟒蛇式的方法是使用字典理解:
def index_responses(a):
    return {f'Q{str(i)}': x for i, x in enumerate(a, 1)}

print(index_responses(['a', 'b', 'c']))
print(index_responses(['d','d','b','e','e','e','d','a']))

# {'Q1': 'a', 'Q2': 'b', 'Q3': 'c'}
# {'Q1': 'd', 'Q2': 'd', 'Q3': 'b', 'Q4': 'e', 'Q5': 'e', 'Q6': 'e', 'Q7': 'd', 'Q8': 'a'}