cols = 'ABC'
ind = range(3)
value=[]
dic = {}
for c in cols:
for i in ind:
value.append(str(c) + str(i))
dic[c] = value
print(dic)
输出:
{'A': ['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C0', 'C1', 'C2'], 'B': ['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C0', 'C1', 'C2'], 'C': ['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C0', 'C1', 'C2']}
为什么我得到上面的输出?
我希望输出像
输出:
{'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2'], 'C': ['C0', 'C1', 'C2']}
答案 0 :(得分:3)
因为每个值都使用相同的对象value
。
您应该在value = []
块中插入for c in cols:
,
但这是更Python化的方式:
cols = 'ABC'
ind = range(3)
dic = {
c: [c + str(i) for i in ind]
for c in cols
}
print(dic)
输出:
{'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2'], 'C': ['C0', 'C1', 'C2']}
答案 1 :(得分:0)
这很简单,每次迭代后都必须重置数组
cols = 'ABC'
ind = range(3)
dic = {}
for c in cols:
value=[]
for i in ind:
value.append(str(c) + str(i))
dic[c] = value
print(dic)
结果:
{'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2'], 'C': ['C0', 'C1', 'C2']}
答案 2 :(得分:0)
cols = 'ABC'
dic = {c:[c + str(x) for x in range(3)] for c in cols}
print(dic)
输出:
{'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2'], 'C': ['C0', 'C1', 'C2']}
答案 3 :(得分:-1)
def make_df(cols, ind):
# Create a DataFrame
data = {c: [str(c) + str(i) for i in ind] for c in cols}
return pd.DataFrame(data, ind)
# Example DataFrame
make_df('ABC', range(3))