【问题标题】:Appending the elements of a list whose indices are indices of a certain integer in a different list附加列表的元素,其索引是不同列表中某个整数的索引
【发布时间】:2023-03-24 09:45:01
【问题描述】:

下面是我的错误代码:

   n = int(input())
   coins = list(map(int,input().split()))
   workertype = list(map(int,input().split()))
   a1 = []
   a2 = []
   a3 = []
   for i in range(n):
     if(workertype[i]==1):
       a1.append(coins[i])

   elif(workertype[i]==2):
      a2.append(coins[i])

   elif(workertype[i]==3):
      a3.append(coins[i])
   print(a1,a2,a3)

coinsworkertype 是两个长度相等的列表。我希望列表a1 具有列表coins 的那些元素,其索引是1(全1)出现在列表workertype 中的元素。 a2a3 相同,但对于所有 2s 和 3s。

这是我的输出

    1(#input for n)
    5 6 7 5 9 10 8(#coins)
    1 2 3 3 2 2 1(#workertype)
    [5] [] [](a1, a2, a3)

我希望 a1、a2、a3 分别为 [5,1]、[6,9,10]、[7,5],而不是这个。

【问题讨论】:

  • 你为什么不把a做成一个列表列表,这样你就可以直接使用索引了?当coinsworkertype 必须至少有n 个元素(但未选中)时,为什么要问n
  • 您的确切输入和错误是什么?
  • 您的缩进已关闭-您可以edit您的问题并解决它吗?
  • 如果n 为1,为什么它会比第一个元素添加更多?
  • 我明白了。谢谢。

标签: python arrays list python-3.5


【解决方案1】:

如果你输入 7(硬币的长度和工人类型)作为 n,它应该可以工作。

【讨论】:

  • 哦,我的错。我很困惑。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-03
  • 2020-08-25
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-17
相关资源
最近更新 更多