【问题标题】:subtract nth item from list from nth item in different list in Python从Python中不同列表中的第n个项目中减去第n个项目
【发布时间】:2017-11-08 15:11:07
【问题描述】:

我要修改这段代码:

def differenceinX(list1,list2):
    answer=[n1 - n2 for (n1, n2) in zip(list1, list2)]
    return answer

类似于:

def differenceinX[x](list1[x],list2[x]):
    answer=[n1 - n2 for (n1, n2) in zip(list1[x], list2[x])]
    return answer

我有 2 个列表 (23,24,26), (24,24,25),我希望能够从第二个列表中的第一个项目中减去第一个列表中的第一个项目。我收到错误消息“无效语法”

【问题讨论】:

  • "从第二个列表中的第一个项目中减去第一个列表中的第一个项目" 那么为什么for 循环呢? return list2[0] - list1[0]
  • 显示您期望的输出示例。

标签: python list subtraction


【解决方案1】:

我认为这会满足您的需求,

def differenceinX(list1,list2, index):
  answer = list1[index] - list2[index]
  return answer

【讨论】:

  • 你不需要给变量 answer 赋值,直接返回即可。
【解决方案2】:

如果您只是将输出作为一个列表项的单个数字查找,请使用以下命令:

def differenceinX(list1, list2, x):
    return list1[x] - list2[x]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 2015-11-01
    • 1970-01-01
    • 2015-09-22
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多