[英]Separate specific characters in a list with strings
我有这个清单:
List:
00001:GR00034.asd
00001:GR00020.asd
00001:GR00002.asd
...
我想将这些行转换成这样:
List:
GR34
GR20
GR2
...
我试过使用循环,但我不能让它工作:
(索引是之前呈现的第一个列表)
for idx in indexes: #to limit between the ":" and the "."
i = ((idx).index(":"))
f = ((idx.index(".")))
idx = idx[i+1:f]
list1 = []
for pos in idx: #Iterate trough each character in idx
if pos.isalpha():
list1.append(pos)
else:
if pos != "0":
list1.append(pos)
if idx[-1] == 0: #to add a 0 at the end if necessary
list1+=0
我的 output 是这样的:
Index List:
1 G
2 R
3 2
4 1
(刚刚出现最后一次迭代并分开)
我没有足够的声誉来发表评论,所以要添加到 patrick7 的帖子中,最后两行应该有 0 作为字符串,而不是 integer
if idx[-1] == "0": #to add a 0 at the end if necessary
list1+="0"
所以问题出在你的“list1”变量嵌套在for循环内。 这意味着每次迭代循环时, list1 都会被重置。 为避免这种情况,您必须在循环之外定义 list1 并在每个循环结束时定义 append 。 例如:
list1 = []
for idx in indexes: #to limit between the ":" and the "."
i = ((idx).index(":"))
f = ((idx.index(".")))
idx = idx[i+1:f]
entry = ""
for pos in idx: #Iterate trough each character in idx
if pos.isalpha():
entry = entry + pos
else:
if pos != "0":
entry = entry + pos
if idx[-1] == '0': #to add a 0 at the end if necessary
entry = entry + '0'
list1.append(entry)
在这里,我定义了一个新变量“entry”,它将通过循环添加所有所需的字符,在循环重置之前,我将 append 条目添加到 list1,为我们提供字符“G”“R”和非零。
这给出了 output: ['GR34', 'GR20', 'GR2']
这是使用正则表达式和列表综合来完成任务的一种更短的方法。 我的正则表达式基于这种格式:GR00020.asd
import re as regex
main_list = ['00001:GR00034.asd', '00001:GR00020.asd', '00001:GR00002.asd']
extracted_items = [regex.search(r'(GR)(:?\d{3})(\d{2})(:?.asd)', item) for item in main_list]
final_list = [''.join(f'{item.group(1)}{item.group(3)}') for item in extracted_items]
print(final_list)
['GR34', 'GR20', 'GR02']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.