如何为包含整数的列表提取字符串?

问题描述 投票:2回答:4

我想从列表中提取字符串。这是我的清单。

[['Lions 3', ' Snakes 3'], ['Tarantulas 1', ' FC Awesome 0'],
 ['Lions 1', ' FC Awesome 1'], ['Tarantulas 3', ' Snakes 1'],
 ['Lions 4', ' Grouches 0']]

这就是我所尝试的:if语句在for循环中迭代遍历列表。

if items[0][-1] == items[1][-1]:
    print('Draw for {} & {}'.format(items[0][:4], items[1][1:]))

输出:

画狮子3和蛇3

期望的输出:

为狮子和蛇画画

没有整数

python python-3.x list python-requests pycharm
4个回答
0
投票

拆分将抓住所有数字,而不仅仅是最后一个,并帮助您处理高分,如11,12 ...正确的分裂有助于处理像'FC Awesome'这样的多字队。

for left, right in lst:
    lteam, lscore = left.strip().rsplit(' ', 1)
    rteam, rscore = right.strip().rsplit(' ', 1) 

    if lscore == rscore:
         print('Draw for {} & {}'.format(lteam, rteam))

Strip删除尾随或初始空格。


1
投票

您可以使用

import re

reg_exp = re.compile(r"[A-Za-z]+")
my_string = "String 3"
reg_exp.search(my_string).group(0) // outputs 'String'

当然你需要调整它到你的循环来提取所需的字符串


0
投票

这是你可以尝试的。

>>> 
>>> items = [['Lions 3', ' Snakes 3'], ['Tarantulas 1', ' FC Awesome 0'], ['Lions 1', ' FC Awesome 1'], ['Tarantulas 3', ' Snakes 1'], ['Lions 4', ' Grouches 0']]
>>> 
>>> output = [[s.split()[0] for s in item] for item in items]
>>> output
[['Lions', 'Snakes'], ['Tarantulas', 'FC'], ['Lions', 'FC'], ['Tarantulas', 'Snakes'], ['Lions', 'Grouches']]
>>> 

最后,这是你可以尝试获得你的o / p。

>>> for item in output:
...     print('Draw for {} & {}'.format(item[0], item[1]))
... 
Draw for Lions & Snakes
Draw for Tarantulas & FC
Draw for Lions & FC
Draw for Tarantulas & Snakes
Draw for Lions & Grouches
>>> 

0
投票

得出一些结论:

matches = [['Lions 3', 'Snakes 3'], 
           ['Tarantulas 1', 'FC Awesome 0'],
           ['Lions 1', 'FC Awesome 1'], 
           ['Tarantulas 3', 'Snakes 1'],
           ['Lions 4', 'Grouches 0']]

def split_team_and_score(team_and_score):
    team, _, raw_score = team_and_score.rpartition(" ") 
    return team, int(raw_score)

for team_and_score_1, team_and_score_2 in matches:
    team1, score1 = split_team_and_score(team_and_score_1)
    team2, score2 = split_team_and_score(team_and_score_2)
    if score1 == score2:
        print('Draw for {} & {}'.format(team1, team2))
© www.soinside.com 2019 - 2024. All rights reserved.