python - Python-从函数调用中去掉括号?
问题描述
我正在编写一个带有 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' (etc...)
我该如何清理输出?
感谢您的任何回复。
解决方案
在循环中使用"Q" + str(key)
or 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
实际上是函数的输入。
获得相同结果的更简洁和更 Pythonic 的方法是使用字典理解:
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'}