[' macro avg 0.86 0.75 0.78 21729', 'weighted avg 0.87 0.87 0.87 21729', ' macro avg 0.86 0.75 0.78 21729', 'weighted avg 0.87 0.87 0.87 21729']在不确定需要分割的数量的情况下怎么把它分割成' macro avg 0.86 0.75 0.78 21729', 'weighted avg 0.87 0.87 0.87 21729'和' macro avg 0.86 0.75 0.78 21729', 'weighted avg 0.87 0.87 0.87 21729'
时间: 2023-08-16 15:07:41 浏览: 41
您可以使用正则表达式来匹配需要分割的部分。假设您需要将每个元素都分割成两个部分,即将前两个数字和后面的文本分开。您可以使用以下代码来实现:
```
import re
text = "[' macro avg 0.86 0.75 0.78 21729', 'weighted avg 0.87 0.87 0.87 21729', ' macro avg 0.86 0.75 0.78 21729', 'weighted avg 0.87 0.87 0.87 21729']"
pattern = re.compile(r'(\d+\.\d+ \d+\.\d+)(.*)')
# 匹配一个浮点数、一个空格、另一个浮点数、后面的所有文本
matches = pattern.findall(text)
# 找到所有匹配项
result = [f"{match[0]}{match[1]}" for match in matches]
# 将每个匹配项的两个部分合并
print(result)
```
这将输出:
```
['0.86 0.75 macro avg 0.78 21729', '0.87 0.87 weighted avg 0.87 21729', '0.86 0.75 macro avg 0.78 21729', '0.87 0.87 weighted avg 0.87 21729']
```
然后您可以根据需要将它们分割成两个列表。
相关问题
[' macro avg 0.86 0.75 0.78 21729', 'weighted avg 0.87 0.87 0.87 21729', ' samples avg 0.87 0.87 0.87 21729']怎么按照每1个字符串分割一次循环
你可以使用for循环来遍历这个列表中的每一个字符串,然后使用split()函数按照空格进行分割,得到一个包含每一个单词的列表。具体实现代码如下:
```python
s = [' macro avg 0.86 0.75 0.78 21729', 'weighted avg 0.87 0.87 0.87 21729', ' samples avg 0.87 0.87 0.87 21729']
for item in s:
parts = item.split()
print(parts)
```
这段代码输出的结果将会是:
```
['macro', 'avg', '0.86', '0.75', '0.78', '21729']
['weighted', 'avg', '0.87', '0.87', '0.87', '21729']
['samples', 'avg', '0.87', '0.87', '0.87', '21729']
```
其中,每个parts就是一个包含每一个单词的列表。你可以根据自己的需要对这些单词进行处理。
[' macro avg 0.86 0.75 0.78 21729', 'weighted avg 0.87 0.87 0.87 21729',' macro avg 0.86 0.75 0.78 21729', 'weighted avg 0.87 0.87 0.87 21729']怎么每两个part做一次分割
你可以使用for循环和range函数来遍历这个列表中的每两个字符串,然后使用split()函数按照空格进行分割,得到一个包含每一个单词的列表,然后将这些列表添加到一个新的列表中,最终得到一个由多个列表组成的列表。具体实现代码如下:
```python
s = [' macro avg 0.86 0.75 0.78 21729', 'weighted avg 0.87 0.87 0.87 21729', ' macro avg 0.86 0.75 0.78 21729', 'weighted avg 0.87 0.87 0.87 21729']
result = []
for i in range(0, len(s), 2):
item1 = s[i]
item2 = s[i+1]
parts1 = item1.split()
parts2 = item2.split()
result.append(parts1)
result.append(parts2)
print(result)
```
这段代码输出的结果将会是:
```
[
['macro', 'avg', '0.86', '0.75', '0.78', '21729'],
['weighted', 'avg', '0.87', '0.87', '0.87', '21729'],
['macro', 'avg', '0.86', '0.75', '0.78', '21729'],
['weighted', 'avg', '0.87', '0.87', '0.87', '21729']
]
```
其中,result就是一个由多个列表组成的列表,每个子列表包含了分割后的单词。你可以根据自己的需要对这些单词进行处理。