[英]Is there a way to find the 0th index a variable amount of times?
我真的沒有充分的理由需要知道這一點,但是是否有可能找到第 0 個索引一定次數? 說你有這段代碼
ar = [[[["a"]]]]
print(ar[0][0][0][0])
但是您可以像ar([0]*4)
那樣做而不是 4 [0][0][0][0]
。 無論如何,感謝您的幫助。
你想做的事情聽起來很奇怪,因為你很少會遇到嵌套結構未知的情況。 也就是說,當您遇到“多次執行 X”類型的問題時,您應該首先想到的就是循環。
例如,您可以將ar
設置為ar
的第零個元素,只要ar
是類型list
的實例並且也不為空。
ar = [[[["a"]]]]
while isinstance(ar, list) and len(ar) > 0:
ar = ar[0]
print(ar) # output: a
注意:如果您是初學者,則len(ar) > 0
只是為了清楚起見。 空列表是錯誤的,所以你也可以while isinstance(ar, list) and ar:
您還可以指定可以向下鑽取的次數以及要向下鑽取的索引:
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
或者,您可以使用遞歸 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
您可以使用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.