字符串中逗号隔开的数字
时间: 2023-09-14 20:09:39 浏览: 36
您可以使用以下代码将逗号隔开的数字字符串转换为数字列表:
```python
s = "1,2,3,4,5"
num_list = list(map(int, s.split(",")))
print(num_list)
```
输出:
```
[1, 2, 3, 4, 5]
```
其中,`split` 方法用于将字符串按照逗号分割成一个列表,`map` 方法用于将列表中的每个元素转换为整型,最后使用 `list` 方法将其转换为列表。
相关问题
mysql 字符串逗号隔开转多行
可以使用MySQL内置函数`replace`和`substring_index`来将逗号隔开的字符串转为多行,具体做法如下:
假设我们有一个表`t`,其中有一个字段`str`存储了逗号隔开的字符串:
```
mysql> select * from t;
+----+--------------+
| id | str |
+----+--------------+
| 1 | a,b,c |
| 2 | d,e,f,g,h,i |
+----+--------------+
```
我们想将这个逗号隔开的字符串转为多行,可以使用如下SQL语句:
```
mysql> select id, replace(substring_index(str, ',', n), ' ', '') as str
from t
join (select 1 as n union all select 2 union all select 3 union all select 4
union all select 5 union all select 6 union all select 7) nums
on char_length(str)
- char_length(replace(str, ',', ''))
>= n - 1;
```
解释一下上面的SQL语句:
- `substring_index(str, ',', n)`:取出逗号隔开的字符串中第n个逗号前的子串;
- `replace(..., ' ', '')`:去除取出的子串中的空格;
- `join (select 1 as n union all select 2 union all select 3 union all select 4
union all select 5 union all select 6 union all select 7) nums`:使用一个子查询`nums`生成一个包含数字1~7的临时表,用于将逗号隔开的字符串转为最多7行;
- `char_length(str) - char_length(replace(str, ',', ''))`:计算逗号隔开的字符串中逗号的个数;
- `>= n - 1`:将第n个逗号前的子串转为一行时,需要保证逗号的个数不少于n-1个。
执行上面的SQL语句后,可以得到如下结果:
```
+----+------+
| id | str |
+----+------+
| 1 | a |
| 1 | b |
| 1 | c |
| 2 | d |
| 2 | e |
| 2 | f |
| 2 | g |
| 2 | h |
| 2 | i |
+----+------+
```
其中,每个逗号隔开的子串已经被转为了多行。
python输出一串数字逗号隔开
你可以使用字符串的join方法将数字列表转换为逗号分隔的字符串,如下所示:
```python
numbers = [1, 2, 3, 4, 5]
output = ', '.join(str(num) for num in numbers)
print(output)
```
输出结果为:
```
1, 2, 3, 4, 5
```
在这个例子中,我们首先将数字列表中的每个元素转换为字符串,然后使用逗号和空格将它们连接起来。