因此,我正在编写一个使预算自动化的程序。我正在尝试在以前不属于预算的最新数据中考虑费用。这个想法是创建一个列表,存储每个月的费用值。我从0列表开始,因为前几个月我们从未见过费用为0,现在我想使用一个for循环来插入本月的值,但似乎没有任何帮助将不胜感激。
new_expenses = ["petrol", "phone"]
new_expense_values = [""120", "20"]
final_expense_data = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0,]]
for i in new_expense_values:
for j in range(len(new_expenses)):
final_expense_data[j][0] = i
print(final_expense_data)
答案 0 :(得分:0)
在您的代码中,您首先将120
写入final_expense_data
中的两个列表,然后再将20
写入两个列表(由于for i in new_expense_values:
循环)。您应该对迭代的所有列表使用相同的索引:
new_expenses = ["petrol", "phone"]
new_expense_values = ["120", "20"]
final_expense_data = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0,]]
for j in range(len(new_expenses)):
final_expense_data[j][0] = new_expense_values[j]
print(final_expense_data)
[['120', 0, 0, 0, 0, 0], ['20', 0, 0, 0, 0, 0]]
但是我建议您使用字典而不是其他列表。 更容易远:
from pprint import pprint
final_expense_data = {
'petrol': [0, 0, 0, 0, 0, 0],
'phone': [0, 0, 0, 0, 0, 0],
'waka': [0, 0, 0, 0, 0, 0]
}
new_expenses = {
'petrol': 120,
'phone': 20,
'big_red_hat': 11111
}
for e in new_expenses:
if e in final_expense_data:
final_expense_data[e][0] = new_expenses[e]
else:
final_expense_data[e] = [0, 0, 0, 0, 0, 0]
final_expense_data[e][0] = new_expenses[e]
pprint(final_expense_data)
{'big_red_hat': [11111, 0, 0, 0, 0, 0], 'petrol': [120, 0, 0, 0, 0, 0], 'phone': [20, 0, 0, 0, 0, 0], 'waka': [0, 0, 0, 0, 0, 0]}
答案 1 :(得分:0)
在此行中,没有意义使用double for循环:
for i in new_expense_values:
在第一阶段,您将拥有:
[['120', 0, 0, 0, 0, 0], ['120', 0, 0, 0, 0, 0]]
第二遍,您将覆盖:
[['20', 0, 0, 0, 0, 0], ['20', 0, 0, 0, 0, 0]]
代码:
new_expenses = ["petrol", "phone"]
new_expense_values = ["120", "20"]
final_expense_data = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0,]]
for j in range(len(new_expenses)):
final_expense_data[j][0] = new_expense_values[j]
print(final_expense_data)
输出:
[['120', 0, 0, 0, 0, 0], ['20', 0, 0, 0, 0, 0]]