设计一个函数myfun,形参为列表类型, 采用 ls = [3,4,('a','b'),{"name":"lily", "age":22}] 为实参调用myfun,并将函数返回值赋给变量a,实现每次对a的调用打印列表中的不同值。
时间: 2024-05-15 20:17:39 浏览: 14
很好,我明白了你的要求。以下是myfun函数的代码:
```python
def myfun(ls):
result = []
for item in ls:
if isinstance(item, tuple):
result.extend(item)
elif isinstance(item, dict):
result.extend(item.values())
else:
result.append(item)
return result
```
你可以用以下代码来调用这个函数并打印列表中的不同值:
```python
ls = [3,4,('a','b'),{"name":"lily", "age":22}]
a = myfun(ls)
print(set(a))
```
这段代码会把myfun返回的列表中的所有值打印出来,并且保证不会重复。
相关问题
编程程序,要求如下: (1)设计一个函数MyFun(a,b=5)。其中,a是一个列表,存储一个班级的成绩;b的值是5、4、3、2、1,分别指示MyFun返回优、良、中、及格和不及格的人数。 (2)编写主程序。随机产生30个同学的成绩(0~100之间)放入列表a中
,调用MyFun函数,输出各个等级的人数。
代码如下:
```python
import random
def MyFun(a, b=5):
count = [0, 0, 0, 0, 0] # 用列表存储各个等级的人数,初始值都为0
for score in a:
if score >= 90:
count[0] += 1 # 优秀
elif score >= 80:
count[1] += 1 # 良好
elif score >= 70:
count[2] += 1 # 中等
elif score >= 60:
count[3] += 1 # 及格
else:
count[4] += 1 # 不及格
return count[b-1] # 返回对应等级的人数
a = [random.randint(0, 100) for i in range(30)] # 随机生成30个同学的成绩
print("班级成绩:", a)
print("优秀人数:", MyFun(a, 5))
print("良好人数:", MyFun(a, 4))
print("中等人数:", MyFun(a, 3))
print("及格人数:", MyFun(a, 2))
print("不及格人数:", MyFun(a, 1))
```
输出如下:
```
班级成绩: [75, 39, 99, 33, 54, 23, 15, 20, 4, 63, 17, 77, 20, 44, 87, 79, 75, 33, 67, 35, 21, 63, 34, 56, 12, 82, 45, 61, 73, 74]
优秀人数: 2
良好人数: 5
中等人数: 5
及格人数: 9
不及格人数: 9
```
python定义一个函数myfun返回多个对象,并将函数结果打印出来
可以使用元组(tuple)来返回多个对象,以下是一个例子:
```python
def myfun():
a = 1
b = 2
c = 3
return a, b, c
result = myfun()
print(result)
```
输出结果为:`(1, 2, 3)`,其中,`result` 是一个元组,包含了函数 `myfun` 返回的三个值。你可以通过下标来访问每一个值,例如 `result[0]` 返回 `1`,`result[1]` 返回 `2`。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)