用字符串分隔列表中的特定字符
Separate specific characters in a list with strings
我有这个列表:
List:
00001:GR00034.asd
00001:GR00020.asd
00001:GR00002.asd
...
我想将这些行转换成这样:
List:
GR34
GR20
GR2
...
我试过使用循环,但我无法让它工作:
(indexes 是之前呈现的第一个列表)
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
我的输出是这样的:
Index List:
1 G
2 R
3 2
4 1
(刚出现last次迭代并分开)
所以问题源于您的“list1”变量嵌套在 for 循环中。这意味着每次迭代循环时,list1 都会重置。为避免这种情况,您必须在循环外定义 list1 并在每个循环结束时附加到它。例如:
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”,它将通过循环添加所有需要的字符,在循环重置之前,我将 entry 附加到 list1 中,为我们提供字符“G”、“R”和 non-zeros.
这给出了输出:
['GR34'、'GR20'、'GR2']
我没有足够的声誉来评论,所以要添加到 patrick7 的 post,最后两行应该有 0 作为字符串,而不是整数
if idx[-1] == "0": #to add a 0 at the end if necessary
list1+="0"
我有这个列表:
List:
00001:GR00034.asd
00001:GR00020.asd
00001:GR00002.asd
...
我想将这些行转换成这样:
List:
GR34
GR20
GR2
...
我试过使用循环,但我无法让它工作:
(indexes 是之前呈现的第一个列表)
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
我的输出是这样的:
Index List:
1 G
2 R
3 2
4 1
(刚出现last次迭代并分开)
所以问题源于您的“list1”变量嵌套在 for 循环中。这意味着每次迭代循环时,list1 都会重置。为避免这种情况,您必须在循环外定义 list1 并在每个循环结束时附加到它。例如:
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”,它将通过循环添加所有需要的字符,在循环重置之前,我将 entry 附加到 list1 中,为我们提供字符“G”、“R”和 non-zeros.
这给出了输出: ['GR34'、'GR20'、'GR2']
我没有足够的声誉来评论,所以要添加到 patrick7 的 post,最后两行应该有 0 作为字符串,而不是整数
if idx[-1] == "0": #to add a 0 at the end if necessary
list1+="0"