Python 根据参数取消列表嵌套一定次数
我尝试n次取消列表,其中n被传递到函数中。在最里面的列表中只能有一个值,这只是删除括号的问题 我试过:Python 根据参数取消列表嵌套一定次数,python,list,loops,nested,Python,List,Loops,Nested,我尝试n次取消列表,其中n被传递到函数中。在最里面的列表中只能有一个值,这只是删除括号的问题 我试过: def nest(x,n): newlist = [x] flatlist=[] if n > 0: for counter in range(n-1): newlist = [newlist] return newlist elif n<0: for sublist in x:
def nest(x,n):
newlist = [x]
flatlist=[]
if n > 0:
for counter in range(n-1):
newlist = [newlist]
return newlist
elif n<0:
for sublist in x:
for item in sublist:
print(item)
return flatlist
else:
return x
print(nest([[["hello"]]], -3))
def嵌套(x,n):
新列表=[x]
平面列表=[]
如果n>0:
对于范围(n-1)内的计数器:
newlist=[newlist]
返回新列表
elif n这可能有效,您可能需要调整它
def unnest(x):
x2 = []
for i in x:
for j in i:
x2.append(j)
return x2
def nest(x,n):
x2 = x
for i in range(n):
x2 = unnest(x2)
return x2
这将根据您的需要进行嵌套:
lst1=[[“你好”]]
str1=‘你好’
def嵌套(元素,n):
返回[nest(元素,n-1)]如果n个元素
打印(嵌套(str1,5))
#[hello'.][-][-][-]
这将解压列表列表的列表。。。递归地
def展平列表(lst):
“”“返回平面列表”“”
如果isinstance(lst,(列表,元组)):
如果len(lst)==0:
返回[]
首先,rest=lst[0],lst[1:]
返回展平列表(第一)+展平列表(其余)
其他:
返回[lst]
def展平到字符串(lst):
“”“将平面列表提取为字符串”“”
返回展平列表(lst)[0]
打印(平展到字符串([[“hello”]]))
#你好
打印(展平列表([hello”]],[hello”][
#[“你好”,“你好”]
当n
为负数时,我无法真正理解代码中的逻辑,但如果我正确理解了问题,并且您只想在输入列表周围添加/删除括号,以下代码就可以了:
def nest(x, n):
if n > 0:
for _ in range(n):
x = [x]
if n < 0:
for _ in range(-n):
x = x[0]
return x
请注意,如果指定的n
大于括号数,则如果内部元素是字符串,则可能会产生意外结果:
print(nest([[["hello"]]], -4))
# h
您可能不希望这样,因此在本例中,我们需要返回内部元素,或者引发错误:
def nest(x, n):
if n > 0:
for _ in range(n):
x = [x]
if n < 0:
for _ in range(-n):
if not isinstance(x, list):
break # or raise ValueError('Not enough nested levels to unpack')
x = x[0]
return x
print(nest([[["hello"]]], -4))
# hello
def嵌套(x,n):
如果n>0:
对于范围内的u(n):
x=[x]
如果n<0:
对于范围内的(-n):
如果不存在(x,列表):
break#或raise ValueError('嵌套级别不足,无法解包')
x=x[0]
返回x
打印(嵌套([[“hello”]]],-4))
#你好
我得到的输出是['hello'][
对不起,结果中的括号太多了。我得到输出['hello'],这仍然是一个括号太多。该代码的预期输出在任何列表之外都有“hello”
def nest(x, n):
if n > 0:
for _ in range(n):
x = [x]
if n < 0:
for _ in range(-n):
if not isinstance(x, list):
break # or raise ValueError('Not enough nested levels to unpack')
x = x[0]
return x
print(nest([[["hello"]]], -4))
# hello