【问题标题】:how to insert duplicate index in list如何在列表中插入重复索引
【发布时间】:2017-05-24 19:49:29
【问题描述】:
idx = []
for i in all_users:

   self.query(*i)
   if self.query(*i) == True:
       print("yes")
   else:
       print("No")
       rem = all_users.index(i)
       idx.append(rem)

print(list(idx))

所以这行得通,但问题是当 all_users 中存在重复值并且 self.query 为 false 时,它​​会插入该值的第一个索引。

e.g, all_users = [[2,5,7,9,4], [17,18], [4], [17,18], [5]]
idx = [1,2,1]

idx = [1,2,3] #correct

所以如果我在 all_users 中有一个空列表,并且我不想将它传递给查询函数,我如何将它附加到 idx 中? #已编辑

【问题讨论】:

  • self.query(*i) 是做什么的?你试图完成什么,从你的代码中并不清楚,事实上,你的代码包含很多我们不知道的东西。如果您需要帮助,您需要提供可重复的示例。理想情况下,一个明确的问题陈述。
  • 我怀疑您的问题来自使用rem = all_users.index(i),它总是会为您提供第一个匹配索引。相反,您应该使用enumerate 遍历索引和元素,如下所示:for i, e in enumerate(all_users): do_stuff_with_index(i); do_stuff_with_element(e)
  • 它返回一个布尔值,如果返回false,对于all_user中的列表,应该插入列表的索引。
  • 对,所以你应该按照我上面说的去做。此外,if self.query(*i) == True: 应该是 if self.query(*i):,并且print(list(idx))list 有一个冗余调用,因为idx已经是一个列表,除非你打算创建并丢弃一个无缘无故复制。

标签: python list python-3.x append


【解决方案1】:

我建议您使用range 长度为all_usersloop,以便您跟踪index,例如:

idx = []
for i in range(len(all_users)):

   self.query(*all_users[i])
   if self.query(*all_users[i]) == True:
       print("yes")
   else:
       print("No")
       idx.append(i)

print(list(idx))

【讨论】:

  • 你真的应该使用enumerate
  • 另外,它被标记为 Python 3,所以这将抛出一个 NameError,因为 xrange 不会被定义。你只需要range,但同样,你真的想要枚举
  • 所以如果我在 all_users 中有一个空列表,并且我不想将它传递给查询函数,我如何将它附加到 idx 中?
  • 我不知道你的查询函数是做什么的,但是如果你想检查list是否为空你可以使用if all_users[i]: #pass to funcelse: #append index to idx
猜你喜欢
  • 1970-01-01
  • 2021-04-03
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 2021-04-05
  • 2019-01-11
  • 1970-01-01
  • 2019-10-09
相关资源
最近更新 更多