当此列表还包含字母时,如何在列表的前面放置数字0?

问题描述 投票:1回答:3

列表的示例为:

   Name
   KOI-234
   KOI-123
   KOI-3004
   KOI-21
   KOI-4325

而且我只是想使所有这些数字至少包含4个字符,所以它看起来像这样:

   Name
   KOI-0234
   KOI-0123
   KOI-3004
   KOI-0021
   KOI-4325

我已经尝试过此代码,但是我想它会读取'KOI'部分,而不是数字,并且不添加零。

first_list = db['Name']
second_list = []
for pl in first_list:
    second_list.append(pl.zfill(4))

所以,我该如何实现?

python list
3个回答
0
投票

您可以使用format specifications

lst = ['KOI-234', 'KOI-123', 'KOI-3004', 'KOI-21', 'KOI-4325']

['{}-{:0>4}'.format(*i.split('-')) for i in lst]
# ['KOI-0234', 'KOI-0123', 'KOI-3004', 'KOI-0021', 'KOI-4325']

0
投票

您可以使用str.split

n, *d = ['Name', 'KOI-234', 'KOI-123', 'KOI-3004', 'KOI-21', 'KOI-4325']
result = [n, *[f'{a}-{b.zfill(4)}' for a, b in map(lambda x:x.split('-'), d)]]

输出:

['Name', 'KOI-0234', 'KOI-0123', 'KOI-3004', 'KOI-0021', 'KOI-4325']

并且如果您想一般地计算偏移值:

n, *d = ['Name', 'KOI-234', 'KOI-123', 'KOI-3004', 'KOI-21', 'KOI-4325']
_d = [i.split('-') for i in d]
offset = max(map(len, [b for _, b in _d]))
result = [n, *[f'{a}-{b.zfill(offset)}' for a, b in _d]]

输出:

['Name', 'KOI-0234', 'KOI-0123', 'KOI-3004', 'KOI-0021', 'KOI-4325']

0
投票

它不会添加零,因为每个元素/名称已经具有超过4个符号。您可以尝试使用正则表达式:

import re

my_list = ['KOI-123', 'KOI-3004', 'KOI-21']
pattern = r'(?<=-)\w+'  # regex to capture the part of the string after the hyphen

for pl in my_list: 
     match_after_dash = re.search(pattern, pl)    # find the matching object after the hyphen
     pl = 'KOI-' + match_after_dash.group(0).zfill(4)    # concatenate the first (fixed?) part of  string with the numbers part
     print(pl)  # print out the resulting value of a list element
© www.soinside.com 2019 - 2024. All rights reserved.