【问题标题】:I am trying to use a for-loop to insert an element of one list to the first element of each list within a list of lists我正在尝试使用 for 循环将一个列表的元素插入到列表列表中每个列表的第一个元素中
【发布时间】:2019-11-02 05:05:42
【问题描述】:

所以我正在编写一个程序来自动化预算。我试图在以前未包含在预算中的最新数据中考虑费用。这个想法是创建一个列表来存储每个月的费用值。我从一个 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)

【问题讨论】:

  • 修复你的new_expense_values = [""120", "20"] 你有一个额外的" 还有预期的输出是什么?
  • 你能举一个期望输出的例子吗
  • sorry the extra " 只是我输入的不是问题,根本不应该有引号。所需的输出如下:[[120, 0, 0, 0, 0, 0], [20, 0, 0, 0, 0, 0]]

标签: python list for-loop append


【解决方案1】:

在您的代码中,您首先将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]]


但我建议您使用 dicts 而不是不同的列表。使用它们更容易修改您的数据:

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]}

【讨论】:

    【解决方案2】:

    没有意义使用双循环,这一行:

    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]]
    

    【讨论】:

    • 当我运行该代码时,我得到以下信息,[[120, 0, 0, 0, 0, 0], [120, 0, 0, 0, 0, 0]]
    • 从一开始就是这个问题
    • 是的,它的字词相同,我不断在每个子列表中重复相同的元素,不过感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 2021-11-12
    相关资源
    最近更新 更多