繁体   English   中英

拆分字符串列表 - 获取第一个和最后一个元素

[英]Split a List of Strings - to get first and last element

对于列表“风”

wind=['', 'W at 6kph', 'SSE at 14kph', 'SSE at 23kph', 'WSW at 28kph', 'WSW at 15kph', 'S at 9kph', 'SW at 18kph', 'NNW at 6kph']

我想把它分成2个列表。

期望的结果:

wind_direction=['','W','SSE','SSE','WSW','WSW','S','SW','NNW']
wind_strength=[6,14,23,28,15,9,18,6]

我的尝试:

wind_direction=[(y.split(' '))[0] for y in wind]
print(wind_direction)

wind_strength=[(x.split(' '))[2] for x in wind]
print(wind_strength)

wind_strength 的错误是“列表索引超出范围”

谢谢

wind=['', 'W at 6kph', 'SSE at 14kph', 'SSE at 23kph', 'WSW at 28kph', 'WSW at 15kph', 'S at 9kph', 'SW at 18kph', 'NNW at 6kph']
direction, speed = zip(*[item.split(' at ') for item in wind if item])
print(direction)
print(speed)

# use ONE of the next 2 lines if you want to remove kph and convert to int
speed = [int(item.removesuffix('kph')) for item in speed] # in python before 3.9 use rstrip instead of removesuffix
# OR
speed = [int(item[:-3]) for item in speed]
print(speed)

输出

('W', 'SSE', 'SSE', 'WSW', 'WSW', 'S', 'SW', 'NNW')
('6kph', '14kph', '23kph', '28kph', '15kph', '9kph', '18kph', '6kph')
[6, 14, 23, 28, 15, 9, 18, 6]

确切问题的解决方案:

wind=['', 'W at 6kph', 'SSE at 14kph', 'SSE at 23kph', 'WSW at 28kph', 'WSW at 15kph', 'S at 9kph', 'SW at 18kph', 'NNW at 6kph']

wind = wind[1:] # removing the ''

wind_direction=[w.split(' at ')[0] for w in wind]
wind_strength=[w.split(' at ')[1].removesuffix('kph') for w in wind]

wind_direction.insert(0, '') # adding the '' back to 1 of the lists

我认为您的问题不正确,因为数据不匹配:

['','W','SSE','SSE','WSW','WSW','S','SW','NNW'] # len is 9
[6,14,23,28,15,9,18,6] # len is 8

如果您想从列表中删除'' ,然后处理:

wind=['', 'W at 6kph', 'SSE at 14kph', 'SSE at 23kph', 'WSW at 28kph', 'WSW at 15kph', 'S at 9kph', 'SW at 18kph', 'NNW at 6kph']

wind = wind[1:] # removing the ''

wind_direction=[w.split(' at ')[0] for w in wind]
wind_strength=[w.split(' at ')[1].removesuffix('kph') for w in wind]

使用列表理解

wind_direction=[(y.split(' '))[0] for y in wind]
print(wind_direction)

wind_strength=[int((x.split(' ')[2]).split('kph')[0])  for x in wind if x != '']
print(wind_strength)

输出

['', 'W', 'SSE', 'SSE', 'WSW', 'WSW', 'S', 'SW', 'NNW']
[6, 14, 23, 28, 15, 9, 18, 6]

对于python3.9+

wind_direction: list[str] = []
wind_strength: list[int] = []

for s in wind:
    if s == '':
        wind_direction.append(s)
        continue
    items = s.split()
    wind_direction.append(items[0])
    if v := ''.join(i for i in items[2] if i.isdigit()):
        wind_strength.append(int(v))
wind_direction=[]
wind_strength=[]
for z in wind:
    if z=='':
        wind_direction.append('')
        wind_strength.append('')
    else:
        wind_direction.append(z.split(' ')[0])
        wind_strength.append(int(z.split(' ')[2].split('kph')[0]))
print(wind_direction)
print(wind_strength)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM