如何在列表中编辑值

时间:2019-02-03 11:27:02

标签: python list

我有一个包含以下值的列表:

3.303.502.25

3.603.402.15

我想编辑它们,使它们显示如下:

3.30 3.50 2.25

3.60 3.40 2.15

代码(我正在通过chromedriver用硒将其获取)

poster = driver.find_elements_by_class_name("outcomeCollection")
odds = [x.text for x in poster]
print(odds)

我在这里获取值:

['3.75\n3.50\n2.05', '1.28\n6.50\n10.00', '8.00\n5.00\n1.40', '8.50\n5.50\n1.33']

我希望这些显示为

['3.75 3.50 2.05', '1.28 6.50 10.00', '8.00 5.00 1.40', '8.50 5.50 1.33']

更新:

for post in teams, odds_nested:
    cobb = {"Teams": teams, "Odds": odds_nested}
    data = pd.DataFrame(cobb, columns=["Teams", "Odds"])
    data.insert(loc=1, column="Home", value=odds_nested[x][0])
    data.insert(loc=2, column="Draw", value=odds_nested[x][1])
    data.insert(loc=3, column="Away", value=odds_nested[x][2])
    x += 1

它不起作用,我只是获得了odds_nested [1]的值

3 个答案:

答案 0 :(得分:0)

如果目标是在每个X.XX序列之后添加一个空格,则正则表达式是一个很好的工具。

>>> import re
>>> data = [
  '3.303.502.25',
  '3.603.402.15',
]
# The `.rstrip()` cleans out the stray whitespace that would appear
# at the end of the string:
>>> [re.sub(r'(\d.\d\d)', r'\1 ', r).rstrip() for r in data]
['3.30 3.50 2.25', '3.60 3.40 2.15']

# You can also use `re.findall` if you'd prefer a list of lists instead:
>>> [re.findall(r'(\d.\d\d)', r) for r in data]
[['3.30', '3.50', '2.25'], ['3.60', '3.40', '2.15']]

答案 1 :(得分:0)

您正在使用换行符分隔字符串。如果您只想将它​​们分隔在空格上,请进行替换。

odds = ['3.75\n3.50\n2.05', '1.28\n6.50\n10.00', '8.00\n5.00\n1.40', '8.50\n5.50\n1.33']

odds_space_separated = [x.replace('\n',' ') for x in odds]
#Output:
['3.75 3.50 2.05', '1.28 6.50 10.00', '8.00 5.00 1.40', '8.50 5.50 1.33']

此外,如果以后需要使用它们,最好将这些值实际存储为数组。

odds_nested = [x.split() for x in odds]
#Output:
[['3.75', '3.50', '2.05'],
 ['1.28', '6.50', '10.00'],
 ['8.00', '5.00', '1.40'],
 ['8.50', '5.50', '1.33']]

编辑:要打印嵌套数组中的值,可以迭代并使用.join方法。

for row in odds_nested:
    print(" ".join(row))
#Output:
3.75 3.50 2.05
1.28 6.50 10.00
8.00 5.00 1.40
8.50 5.50 1.33

答案 2 :(得分:0)

尝试将replace函数的字符串功能与map函数一起使用:

alist = ['3.75\n3.50\n2.05', '1.28\n6.50\n10.00', '8.00\n5.00\n1.40', '8.50\n5.50\n1.33']
alist = list(map(lambda x: x.replace("\n", " "), alist))
print(alist)

因此,列表的每个项目都会更改。

输出:

['3.75 3.50 2.05', '1.28 6.50 10.00', '8.00 5.00 1.40', '8.50 5.50 1.33']