【问题标题】:Python appends wrong parrameters into listPython将错误的参数附加到列表中
【发布时间】:2014-07-01 17:43:59
【问题描述】:

我在 Python 中有一个问题。 我创建了一种方法,该方法从二维列表中为空列表添加值,该列表是从 .txt 中的数据创建的。 当我选择在一个空列表中附加一个数字 4 和 2 (来自 4 )时,它表明我只添加了 1 , 2 而不是 4 和 2 。问题出在哪里?

这是代码(对不起,代码中的“未知”语言,我是立陶宛人,所以程序必须用这种语言编写) self.PriskirtiDydžiai 是附加值的空列表。 GalimiPriimtiDUOMENYS[0] 是从其中选择数据的二维列表的第一个元素。它是我工作的一部分。它是类方法之一。

   #self.GalimiPriimtiDUOMENYS  This list gets data from .txt   The list looks like that : [1,2,3,4][1,2,3,4,5,6,7,8,9,10]
     def GalimuDydziuPriskyrimas (self,Krovinys):                              
           DYDNR=int(input("write value (from 1 to 4): "))
           if DYDNR>len(self.GalimiPriimtiDUOMENYS[0]):
                print("this number do not exist , try again")
                DYDNR=int(input("write value (from 1 to 4): "))
                self.PriskirtiDydziai.append(self.GalimiPriimtiDUOMENYS[0][DYDNR-1])
           else:
                self.PriskirtiDydziai.append(self.GalimiPriimtiDUOMENYS[0][DYDNR-1])

当我打印名为 GalimiPriimtiDUOMENYS 的列表时,我得到了这个:

    >>>b1.GalimiPriimtiDUOMENYS
    [[1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]

【问题讨论】:

  • 只是调试您的代码,您没有提供所有必需的信息。如果您真的认为,我们会帮助您,提供最短的工作示例,展示您的问题。
  • 缺乏阅读立陶宛语的能力!我建议打印出 GalimiPriimtiDUOMENYS 以查看索引值的位置。似乎您只是弄错了您认为元素在列表中的位置的索引

标签: python list append


【解决方案1】:

你的二维数组看起来像l=[[1,2,3,4],[1,2,3,4,5,6,7,8,9,10]]:

In [5]: l=[[1,2,3,4],[1,2,3,4,5,6,7,8,9,10]]

In [13]: l[0][1] # index of 2
Out[13]: 2

In [14]: l[0][3] # index of four
Out[14]: 4

您要附加 [0][DYDNR-1],这需要输入为 2 才能获得 2 即 [0][2-1] 和 4 才能获得 4 即 l[0][4-1]

如果不运行你的函数,很难看出还有哪里可能出错。

【讨论】:

    猜你喜欢
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多