我正在编写一个带有1个参数的函数,并且希望该参数为列表。 我基本上已经获得了我想要的所有行为,除了一件事情:`
create_file
这些是函数调用:
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']))
但是我需要我的输出看起来更干净,更像是: {(Q1:'a',Q2:'b'(etc ...)
我该如何清理输出?
感谢您的答复。
答案 0 :(得分:0)
在循环中使用"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'}
答案 1 :(得分:0)
我认为您只想将'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']
有更好的方法来计数列表中的项目;我将这些留给您研究。