python 把列表中的数字转化为占列表总数的百分比的列表
时间: 2024-02-06 09:12:05 浏览: 84
可以通过以下方式将列表中的数字转化为占列表总数的百分比的列表:
```
# 假设列表为 nums
percentages = [(num / sum(nums)) * 100 for num in nums]
```
这里先计算出列表中所有元素的和(使用 `sum` 函数),然后遍历列表中的每个元素,将其除以总和并乘以100,以得到其占比,并将结果存储在新的列表中。
相关问题
python 把列表中的数字转化为占列表总数的百分比的带%的列表
可以通过以下方式将列表中的数字转化为占列表总数的百分比的带%的列表:
```
# 假设列表为 nums
percentages = ["{:.2f}%".format((num / sum(nums)) * 100) for num in nums]
```
这里同样先计算出列表中所有元素的和(使用 `sum` 函数),然后遍历列表中的每个元素,将其除以总和并乘以100,以得到其占比,并使用 `"{:.2f}%"` 来格式化为带有两位小数和百分号的字符串,并将结果存储在新的列表中。
python 把列表中的数字列表转化为占列表总数的百分比形成新的列表
假设你有一个包含数字列表的列表 `num_list`,你可以使用以下代码将其转换为占列表总数的百分比形成新的列表 `percent_list`:
```python
total = sum(len(lst) for lst in num_list) # 计算数字列表中的数字总数
percent_list = [[num/total for num in lst] for lst in num_list] # 将数字列表转化为百分比形式
```
在这个代码中,我们使用了列表推导式。首先,我们计算出数字列表中的数字总数,并赋值给变量 `total`。然后,我们使用嵌套的列表推导式将每个数字除以总数,并将其转换为百分比形式。最后,我们将这些百分比数字列表组成的列表赋值给变量 `percent_list`。
阅读全文
相关推荐

















