Python:如何替换嵌套列表中的值?

时间:2018-07-13 05:36:33

标签: python

如何将詹姆斯的薪水从1000改为1500,并打印詹姆斯的数据?

data = [['Ben', 'Manager', 3000],
           ['James', 'Cleaner', 1000],
           ['Ken', 'Supervisor', 2000]]

for (name,appt,salary) in data:
    if name == 'James':
        salary = 1500
        print(linked_data[1]) 

这是我当前的输出:

['James', 'Cleaner', 1000]

预期输出:

['James', 'Cleaner', 1500]

11 个答案:

答案 0 :(得分:5)

您需要找到发生索引的位置。使用enumerate

for idx, (name,appt,salary) in enumerate(data):
    if name == 'James':
        # salary is at index 2 in the inner list
        data[idx][2] = 1500
        print(f"{name},{appt},{salary}")

答案 1 :(得分:1)

您将从for循环中的列表中解压缩,并创建3个变量nameapptsalary。使用此变量,无法轻松更改data的结构。您需要从data中提取一个列表并通过建立索引来访问它:

from pprint import pprint

data = [['Ben', 'Manager', 3000],
           ['James', 'Cleaner', 1000],
           ['Ken', 'Supervisor', 2000]]

for d in data:
    if d[0] == 'James':
        d[2] = 1500
        print(d)  # prints only changed row

pprint(data)  # prints whole structure

打印:

['James', 'Cleaner', 1500]
[['Ben', 'Manager', 3000],
 ['James', 'Cleaner', 1500],
 ['Ken', 'Supervisor', 2000]]

答案 2 :(得分:0)

如果您知道索引,则可以执行以下操作:

data = [['Ben', 'Manager', 3000],
           ['James', 'Cleaner', 1000],
           ['Ken', 'Supervisor', 2000]]


data[1][2] = 1500

print(data[1])

输出:

['James', 'Cleaner', 1500]

答案 3 :(得分:0)

我建议使用字典来存储您的信息,例如:

data = [['Ben', 'Manager', 3000],
        ['James', 'Cleaner', 1000],
        ['Ken', 'Supervisor', 2000]]

data_dict = {k: {'position': p, 'salary': s} for k, p, s in data}

data_dict['James']['salary'] = 1500

print(data_dict)

输出:

{'Ben': {'position': 'Manager', 'salary': 3000}, 'James': {'position': 'Cleaner', 'salary': 1500}, 'Ken': {'position': 'Supervisor', 'salary': 2000}}

如果您需要将其转换回列表,只需使用以下方法即可:

print([[k] + list(v.values()) for k, v in data_dict.items()])

输出:

[['Ben', 'Manager', 3000], ['James', 'Cleaner', 1500], ['Ken', 'Supervisor', 2000]]

答案 4 :(得分:0)

替换工资:

data[1][2] = 1500

要打印数据:

print(data[1])

答案 5 :(得分:0)

现在,您正在尝试遍历对for循环的参数实际上没有意义的三个值。您需要做的是一次访问一个嵌套数组,检查该数组的名称是否为James,如果是,则更改薪水。

data = [['Ben', 'Manager', 3000],
        ['James', 'Cleaner', 1000],
        ['Ken', 'Supervisor', 2000]]

for (person) in data:
    if person[0] == 'James':
        # change index 1 (occupation) to 1500
        person[1] = 1500

print(data)

输出:

[['Ben', 'Manager', 3000],
 ['James', 'Cleaner', 1000],
 ['Ken', 'Supervisor', 2000]]

答案 6 :(得分:0)

您需要先访问列表的第二个子列表,然后再访问子列表的第三元素以进行更改。看看下面的代码:

<div class="container">
  <div class="item">
    <!-- Things with overflowing content -->
  </div>
  <div class="item">
    <!-- Things with overflowing content -->
  </div>
  <div class="item">
    <!-- Things with overflowing content -->
  </div>
</div>

<style>
  .container {
    columns: auto 5;
    column-gap: 0;
    margin: -16px;
  }

  .items {
    break-inside: avoid;
    padding: 16px;
    page-break-inside: avoid;
    will-change: transform;
  }
</style>

答案 7 :(得分:0)

变量salary只是data中值的副本。您应该修改原始列表而不是副本。函数enumerate可以生成从列表中更改值所需的索引(从0开始)。

data = [['Ben', 'Manager', 3000],
       ['James', 'Cleaner', 1000],
       ['Ken', 'Supervisor', 2000]]

for i, (name, appt, salary) in enumerate(data):
    if name == 'James':
        data[i][2] = 1500
        print(data[i])

输出:['James','Cleaner',1500]

答案 8 :(得分:0)

我认为使用类代替2D列表更好。

class Employee:
    def __init__(self, name, job, salary):
        self.name = name
        self.job = job
        self.salary = salary

    def __str__(self):

        return '[{}, {}, {}]'.format(self.name, self.job, self.salary)

    def __repr__(self):

        return '[{}, {}, {}]'.format(self.name, self.job, self.salary)

data = [Employee('James', 'Cleaner', 1000),
        Employee('Ben', 'Manager', 3000)]

print(data)

for employee in data:
   if employee.name == 'James':
    employee.salary = 1500
    print(employee)
print(data)

输出:

[[James, Cleaner, 1000], [Ben, Manager, 3000]]
[James, Cleaner, 1500]
[[James, Cleaner, 1500], [Ben, Manager, 3000]]

答案 9 :(得分:0)

您也可以使用

data = [['Ben', 'Manager', 3000], ['James', 'Cleaner', 1000], ['Ken', 'Supervisor', 2000]]
change = 3000
name = 'Ben'
print([[x, y, change] if x == name else [x, y, z] for x, y, z in data])

因此您得到以下输出: [['Ben','Manager',3000],['James','Cleaner',1000],['Ken','Supervisor',2000]]

答案 10 :(得分:0)

如果要使用Simple For循环,则

val myTuple = (1, 2, 3)

val toPrint = myTuple match {
  case (a, b, c) => s"got $a, $b, and $c"
  case (a, b) => s"got $a and $b"
  case _ => s"Unknown data"
}