Subsetting one list based on values of another list.

huangapple go评论80阅读模式
英文:

Subsetting one lost based on values of other list

问题

根据第二个列表的值,提取第一个列表的值,可以更简洁地编写如下:

List1[4:7]

这样可以避免多次使用 List2 的名称。

英文:

Let say I have below two lists

List1 = [3,4,5,6,8,3,2,4,6,7,8,6]
List2 = [4, 7]

Now, based on the values of the second list, I want to extract the values of the first list. So trivially I would write

List1[List2[0] : List2[1]]

While it is fine, I want to make above line more concise. As you see I had to use the name List2 twice in above line. But to maintain my overall writing style, I want to call List2 only once as minimum number possible (perhaps)

Is there really any way to achieve this?

答案1

得分: 0

print(List1[slice(*List2)])

输出:

[8, 3, 2]
英文:

Try:

print(List1[slice(*List2)])

Prints:

[8, 3, 2]

huangapple
  • 本文由 发表于 2023年8月5日 04:10:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定