简体   繁体   English

在python中替换二维列表中的项目

[英]Replacing items in a two dimensional list in python

I am trying to append the second item in my two dimensional. 我想在我的二维中附加第二个项目。 I have tried a few dozen different ways and can't seem to get it to append. 我已经尝试了几十种不同的方式,似乎无法让它追加。

def main():
    values = [[10,0], [13, 0], [36, 0], [74,0], [22,0]]
    user = int(input('Enter a whole number'))
    for i in range(len(values)):
        print(values[i])

(current out put) (当前输出)

10, 0

13, 0

36, 0

74, 0

22, 0

(were the second part it is values[0] + user input) (第二部分是值[0] +用户输入)

[10, 12]

[13, 15]

[36, 38]

[74, 76]

[22, 24]

with list comprehension 列表理解

user = 2
[[x[0], sum(x)+user] for x in values]
>>> [[10, 12], [13, 15], [36, 38], [74, 76], [22, 24]]

or using map: 或使用地图:

map(lambda x: [x[0], sum(x)+user], values)

First, you can nearly always avoid iterating over range(len(iterable)) - in this case, your loop can be written as the much nicer: 首先,您几乎总能避免迭代range(len(iterable)) - 在这种情况下,您的循环可以写得更好:

for value in values:
    print(value)

for exactly the same functionality. 完全相同的功能。

I'm not sure from your description exactly how you want the code to behave, but it seems like you want something like this - each line of output will have the first item of the corresponding value , and then that added to the user input; 我不确定你的描述究竟是你想要代码的行为,但似乎你想要这样的东西 - 每行输出都会有相应value的第一项,然后添加到用户输入中; ie, ignoring the second item of the existing input entirely: 即完全忽略现有输入的第二项:

for value in values:
    total = value[0] + user
    print((value[0], total))

or if you want it to overwrite the second item of each value for later use in your program: 或者如果您希望它覆盖每个value的第二项以供以后在您的程序中使用:

values = [[10,0], [13, 0], [36, 0], [74,0], [22,0]]
for value in values:
    value[1] = value[0] + user
    print(value)

Shouldn't it be just like this? 不应该这样吗?

>>> def f():
    values = [[10,0], [13, 0], [36, 0], [74,0], [22,0]]
    user = int(input('Enter a whole number'))
    for i in range(len(values)):
        values[i][1]=values[i][0]+user
            print(values[i])


>>> f()
Enter a whole number2
[10, 12]
[13, 15]
[36, 38]
[74, 76]
[22, 24]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM