如何将列表中字符串类型的负数、零转为整数并拆分球队名与数据
解决方案:拆分大型列表为球队名与数字列表
问题描述
40岁开始学习Python,现有一个包含28920个字符串元素的大型列表,示例如下:
small = ['1', 'Manchester City', '3', '3', '0', '0', '14', '2', '12', '9', '2', 'Tottenham Hotspur', '3', '3', '0', '0', '7', '2', '5', '9', '3', 'Arsenal', '3', '3', '0', '0', '8', '4', '4', '9', '4', 'Liverpool', '3', '2', '1', '0', '12', '2', '10', '7', '5', 'Brentford', '3', '2', '1', '0', '10', '3', '7', '7', '6', 'Brighton & Hove Albion', '3', '2', '1', '0', '6', '2', '4', '7', '7', 'Leeds United', '3', '2', '1', '0', '6', '2', '4', '7', '8', 'Fulham', '3', '2', '1', '0', '7', '5', '2', '7', '9', 'Chelsea', '3', '2', '1', '0', '6', '4', '2', '7', '10', 'Manchester United', '3', '2', '0', '1', '6', '4', '2', '6', '11', 'Newcastle United', '3', '1', '2', '0', '5', '3', '2', '5', '12', 'Wolverhampton Wanderers', '3', '1', '2', '0', '2', '1', '1', '5', '13', 'Crystal Palace', '3', '1', '1', '1', '4', '4', '0', '4', '14', 'Southampton', '3', '1', '1', '1', '4', '4', '0', '4', '15', 'Aston Villa', '3', '1', '1', '1', '3', '3', '0', '4', '16', 'AFC Bournemouth', '3', '1', '1', '1', '2', '3', '-1', '4', '17', 'Nottingham Forest', '3', '1', '0', '2', '3', '5', '-2', '3', '18', 'Everton', '3', '0', '2', '1', '1', '2', '-1', '2', '19', 'Leicester City', '3', '0', '1', '2', '3', '5', '-2', '1']
球队名固定位于索引1、11、22、33…的位置,需将球队名以原字符串存入team_names列表,其余元素(包括'0'、负数)转换为整数存入numbers列表并保持原有顺序,目前转换'0'时遇到问题。
解决代码
直接按给定的索引规则拆分列表,用int()转换非球队名元素(int()对'0'、负数均能正确转换):
team_names = [] numbers = [] # 生成所有球队名的索引集合 team_indices = set() current_idx = 1 list_length = len(small) while current_idx < list_length: team_indices.add(current_idx) # 按用户给出的索引规律:第一个球队索引1,下一个11(+10),之后每次+11 if current_idx == 1: current_idx += 10 else: current_idx += 11 # 遍历列表拆分元素 for idx, elem in enumerate(small): if idx in team_indices: team_names.append(elem) else: # 转换为整数,支持0、正数、负数 numbers.append(int(elem))
说明
- 核心逻辑是按固定索引判断球队名,而非通过元素内容判断(避免因球队名含数字、负数无法用
isdigit()识别等问题)。 int('0')会直接转换为整数0,int('-1')转换为-1,完全满足需求。- 若后续发现索引规律有变化,只需调整
team_indices的生成逻辑即可。
内容的提问来源于stack exchange,提问作者user19925544
相关产品推荐
相关产品推荐

