从列表列表中的第一项中删除字符
remove characters from the first items in list of lists
我有一个嵌套列表,在每个列表中,第一项是一个以 .abc
结尾的字符串。我想从我的嵌套列表中删除所有 .abc
个字符。
这是我得到的:
x = [['car.abc', 1, 2], ['ship.abc', 3, 4]]
我希望我的嵌套列表如下:
x = [['car', 1, 2], ['ship', 3, 4]]
我怎样才能做到这一点?
使用简单的 for 循环。
x = [['car.abc', 1, 2], ['ship.abc', 3, 4]]
for i in x:
i[0] = i[0].rsplit(".", 1)[0]
print(x)
使用嵌套正则表达式和列表理解:
>>> import re
>>> [[re.sub(r'.abc$', '', e) if isinstance(e, basestring) else e for e in l] for l in x]
[['car', 1, 2], ['ship', 3, 4]]
isinstance(e, basestring)
检查 e
是否为字符串(参见 this question)。
对于字符串e
,re.sub(r'.abc$', '', e)
替换您指定的部分
否则e
不变
列表 l
中的任何元素 e
以及 x
中的每个 l
都会发生上述情况。
x = [['car.abc', 1, 2], ['ship.abc', 3, 4]]
new_x=[]
for lst in x:
temp_lst=[]
for item in lst:
if(str(item)[-4:] == '.abc'):
item = str(item)[:-4]
temp_lst.append(item)
new_x.append(temp_lst)
print(new_x)
我有一个嵌套列表,在每个列表中,第一项是一个以 .abc
结尾的字符串。我想从我的嵌套列表中删除所有 .abc
个字符。
这是我得到的:
x = [['car.abc', 1, 2], ['ship.abc', 3, 4]]
我希望我的嵌套列表如下:
x = [['car', 1, 2], ['ship', 3, 4]]
我怎样才能做到这一点?
使用简单的 for 循环。
x = [['car.abc', 1, 2], ['ship.abc', 3, 4]]
for i in x:
i[0] = i[0].rsplit(".", 1)[0]
print(x)
使用嵌套正则表达式和列表理解:
>>> import re
>>> [[re.sub(r'.abc$', '', e) if isinstance(e, basestring) else e for e in l] for l in x]
[['car', 1, 2], ['ship', 3, 4]]
isinstance(e, basestring)
检查e
是否为字符串(参见 this question)。对于字符串
e
,re.sub(r'.abc$', '', e)
替换您指定的部分否则
e
不变列表
l
中的任何元素e
以及x
中的每个l
都会发生上述情况。
x = [['car.abc', 1, 2], ['ship.abc', 3, 4]]
new_x=[]
for lst in x:
temp_lst=[]
for item in lst:
if(str(item)[-4:] == '.abc'):
item = str(item)[:-4]
temp_lst.append(item)
new_x.append(temp_lst)
print(new_x)