【问题标题】:one line for loop for 2d list wih variable incrementation and 2d list search用于具有变量递增和 2d 列表搜索的 2d 列表的一行 for 循环
【发布时间】:2015-11-10 09:27:48
【问题描述】:

我是 python 单线循环的新手。

我希望用户将数据输入到二维列表中,同时提醒他他们将输入的数据索引。 我的代码是:

flag=0
x=[[int(input("enter the "+ str(flag)+ "number:")) flag+=1 for x in range(0,col)]for y in range(0,row)] 

以上代码显示语法错误。我应该如何在 for 循环的一行中增加标志值。

接下来我想在二维列表中搜索整数值

x=[[0,3,2],[1,1,1],[9,2,2]]
for i,j in enumerate(x):
    try:
        y=j.index(1)
    except ValueError:
        continue
    print(i,y)

上面的代码适用于单个项目搜索,但我想要列表中每个 1 的索引。而上面的代码只返回它遇到的第一个“1”的索引,即“1 0”

提前谢谢你。

【问题讨论】:

  • 请轻视这条评论,因为我还没有花太多时间回答您的问题。但是你有没有考虑过让你的代码在没有单行代码的情况下工作?扩展你的代码,一旦它工作,如果你必须把它修剪成一个单行。
  • @Torxed 是的,我已经做到了,它工作得很好,但这就是我无法缩小它的问题。顺便说一句,感谢您的建议
  • 亲爱的,你能贴出那个代码吗?我们更容易阅读扩展的代码块,我们可以根据您上面的尝试为您缩小它。
  • @Torxed 我得到了答案,但还是非常感谢。 :)

标签: python arrays python-3.x multidimensional-array


【解决方案1】:

您的问题是列表推导必须产生一个值,而您正试图在其中执行 flag +=1

如果你这样做会更清楚:

>>> flag = 0
>>> row = 1
>>> col = 3
>>> x=[[int(input("enter the number [{}][{}]:".format(y, x))) for x in range(0,col)] for y in range(0,row)]
enter the number [0][0]:1
enter the number [0][1]:2
enter the number [0][2]:3
>>> x
[[1, 2, 3]]

或者,要完全实现您想要的,您可以执行以下操作:

>>> y=[[int(input("enter the {} number:".format(x+y*row))) for x in range(0,col)]for y in range(0,row)]
enter the 0 number:1
enter the 1 number:2
enter the 2 number:3
>>> y
[[1, 2, 3]]

问题第二部分的更新: 您可以为此使用更多列表推导:

>>> y=[[int(input("enter the {} number:".format(x+y*row))) for x in range(0,col)]for y in range(0,row)]
enter the 0 number:0
enter the 1 number:1
enter the 2 number:1
>>> y
[[0, 1, 1]]
>>> for arr in y:
...   print [index for (index, val) in enumerate(arr) if val == 1]
...
[1, 2]

【讨论】:

  • 对于第二部分,我想搜索列表中存在的每个“1”,而我的代码只返回它遇到的第一个“1”的索引,即“1 0”
  • 我已更新为包含您问题第二部分的示例
猜你喜欢
  • 2023-03-19
  • 1970-01-01
  • 2018-04-12
  • 2018-04-02
  • 2018-12-08
  • 2022-07-22
  • 2021-03-01
  • 2014-07-19
  • 1970-01-01
相关资源
最近更新 更多