x_list = ["I", "live", "in", "New", "-", "York", "City", ".", "I", "am" "from", "New", "-", "Delhi"]
这是我的清单。我想要的是在连字符“-”之前和之后加入单词。这样我的清单就变成了。
x_list = ["I", "live", "in", "New-York", "City", ".", "I", "am", "from", "New-Delhi"]
是否有一种简短的方法?
您可以enumerate
d-for
循环:
lst = ["I", "live", "in", "New", "-", "York", "City"]
for index, item in enumerate(lst):
if item == '-':
lst[index-1:index+2] = [''.join(lst[index-1:index+2])]
print(lst) # ['I', 'live', 'in', 'New-York', 'City']
或者,如果您要处理的是简短列表,但很少'-'
(例如您的示例中),则也可以使用while
循环。但是,这具有二次运行时行为,因此'-'
如果您关心性能,请不要将其用于包含大量此类的大型列表:
lst = ["I", "live", "in", "New", "-", "York", "City"]
while '-' in lst:
pos = lst.index('-')
lst[pos-1:pos+2] = [''.join(lst[pos-1:pos+2])]
print(lst) # ['I', 'live', 'in', 'New-York', 'City']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句