输入一个嵌套列表,求其嵌套的层数,写出Python代码
时间: 2024-02-16 10:13:17 浏览: 19
好的,我们可以使用循环和迭代来实现。以下是示例代码:
```python
def nested_depth(lst):
depth = 0
while isinstance(lst, list):
depth += 1
lst = lst[0]
return depth
```
这个函数接受一个列表作为参数,返回其嵌套的层数。我们使用一个 while 循环来不断获取列表的第一个元素,并将 depth 加1,直到列表的第一个元素不再是列表为止。最后返回 depth 即可。需要注意的是,如果传入的不是列表,函数会返回0。
相关问题
用python列表嵌套写出随机密码,要求密码中包含大写字母、小写字母、数字字符。长度八位
可以使用Python的random库和字符串常量来生成随机密码。以下是一个示例代码:
```python
import random
import string
# 定义包含大写字母、小写字母、数字字符的字符集
char_set = string.ascii_uppercase + string.ascii_lowercase + string.digits
# 生成随机密码
password = []
for i in range(8):
password.append(random.choice(char_set))
# 将密码列表转换为字符串
password = ''.join(password)
print(password)
```
输出类似于:`8Ji4oY7G` 的随机密码。
Python写出删除列表中重复的元素,用while循环
可以用以下代码实现:
```python
my_list = [1, 2, 2, 3, 3, 3, 4, 5, 5]
i = 0
while i < len(my_list):
j = i + 1
while j < len(my_list):
if my_list[i] == my_list[j]:
del my_list[j]
else:
j += 1
i += 1
print(my_list)
```
输出结果为:
```
[1, 2, 3, 4, 5]
```
这个程序使用两个嵌套的 while 循环来比较列表中的元素。外层循环遍历列表中的每个元素,内层循环从当前元素的下一个位置开始遍历并比较。如果找到重复元素,就使用 del 语句从列表中删除它。如果没有找到重复元素,就继续比较下一个元素。最后输出去重后的列表。