[英]Is there a way to find the 0th index a variable amount of times?
I don't really have a good reason for needing to know this, but is it possible to find the 0th index a certain amount of times?我真的没有充分的理由需要知道这一点,但是是否有可能找到第 0 个索引一定次数? Say like you have this piece of code
说你有这段代码
ar = [[[["a"]]]]
print(ar[0][0][0][0])
but instead of the 4 [0][0][0][0]
you can just do like ar([0]*4)
.但是您可以像
ar([0]*4)
那样做而不是 4 [0][0][0][0]
。 Anyway, thanks for the help.无论如何,感谢您的帮助。
What you want to do sounds weird because you will rarely run into a situation where you have an unknown nesting structure.你想做的事情听起来很奇怪,因为你很少会遇到嵌套结构未知的情况。 That said, a loop is the first thing you should think of when you encounter a problem of the type "do X a bunch of times".
也就是说,当您遇到“多次执行 X”类型的问题时,您应该首先想到的就是循环。
For example, you could set ar
to the zeroth element of ar
as long as ar
is an instance of type list
and is also not empty.例如,您可以将
ar
设置为ar
的第零个元素,只要ar
是类型list
的实例并且也不为空。
ar = [[[["a"]]]]
while isinstance(ar, list) and len(ar) > 0:
ar = ar[0]
print(ar) # output: a
Note: len(ar) > 0
is just for clarity if you're a beginner.注意:如果您是初学者,则
len(ar) > 0
只是为了清楚起见。 Empty lists are falsey, so you could have also just done while isinstance(ar, list) and ar:
空列表是错误的,所以你也可以
while isinstance(ar, list) and ar:
You could also specify how many times you can drill down and the index to which you want to drill down:您还可以指定可以向下钻取的次数以及要向下钻取的索引:
def drill_down(arg, index, count):
for i in range(count):
if isinstance(arg, list) and len(arg) > index:
arg = arg[index]
return arg
ar = [[[["a"]]]]
result = drill_down(ar)
print(result) # Output: a
Or, you could use a recursive function, which can be made to behave similar to a loop:或者,您可以使用递归 function,其行为类似于循环:
def drill_down(arg, index, count):
if isinstance(arg, list) and len(arg) > index and count > 0:
return drill_down(arg[index], index, count - 1)
return arg
ar = [[[["a"]]]]
result = drill_down(ar)
print(result) # Output: a
You can use functools
and itertools
to define a function that repeatedly indexes into the ith
element of an array count
times:)您可以使用
functools
和itertools
定义一个 function 重复索引到数组count
次的ith
元素:)
import functools
import itertools
find_nth_elem = lambda n, arr: arr[n]
def repeated_index(arr, i, count):
"""Index into `i`th element of `arr` a total of `count` times."""
# get _an iterator of_ `count` copies of the same function, lazy eval
index_calls = itertools.repeat(functools.partial(find_nth_elem, i), count)
# f(f(f(...f(arr)...))), where f(x) = get nth element of x.
return functools.reduce(lambda acc, f: f(acc), index_calls, arr)
arr = [[[["a"]]]]
print(repeated_index(arr, 0, 4))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.