【问题标题】:How to print the values from a list based on indexes?如何根据索引打印列表中的值?
【发布时间】:2021-10-06 19:28:26
【问题描述】:

我在列表中有数据,即 row,我有一个索引列表,即 indexes

如何根据索引打印该数据。

例如

rows = [['1', 'John', '20'],
        ['2', 'Mary', '19'], 
        ['3', 'Alex', '20'], 
        ['4', 'Jaydeep', '24'], 
        ['5', 'Meet', '23'], 
        ['6', 'Parth', '25']
       ]

indexes = [0,1]

那我想打印

for row in rows:
    print(row[0], row[1])

【问题讨论】:

  • 您要打印该索引的行值还是只打印文本行[0]、行[1]、行[2]?
  • 这是一个非常令人困惑的问题..
  • operator.itemgetter(*indexes)(row) 也许。如果您的数据在 numpy 数组中,您可以直接使用 indexes 作为索引,但这对于此功能来说是一个相当大的变化。
  • @liquiddeath 我想打印该索引的行值

标签: python python-3.x list


【解决方案1】:

类似于下面的内容(据我了解的问题..)

row = [7,12,90]
indexs = [2,0,1]
for i in indexs:
  print(row[i])

输出

90
7
12

【讨论】:

  • 但是......我认为没有人理解这个问题
  • 让我们拭目以待,看看 OP 真正在寻找什么 :-)
【解决方案2】:

这个问题令人困惑。如果您正在寻找数组值,请使用 balderman 的答案。从您的问题来看,您需要显示“打印”是可以理解的。在这种情况下使用下面的代码。

row=[1,2,3,4]
indexes=[0,1,2,3]
res="print "
for i in indexes:
    res+=" row[{0}],".format(i)
print(res)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 2017-03-28
    • 1970-01-01
    相关资源
    最近更新 更多