Python:根据长度删除列表中的字符串对象 [英] Python: deleting a string object in a list based on the length
问题描述
如果字符数为5个或更少,我想从列表中删除每个城市.
I want to delete each city from the list if the number of the characters is 5 or less.
cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai"]
j = 0
for i in cities:
if len(i) <= 5:
del cities[j]
j += 1
这仅删除5个字符以内的第一个城市.但第二个不是.
That deletes only the first city which is 5 characters or less. But not the second one.
我也尝试过:
i = 0
while i < len(cities):
if len(cities[i]) <= 5:
del cities[i]
i += 1
但是它给了我相同的结果!
but it gave me the same result!!
更新: 最简单的方法是添加一个切片:
UPDATE: The easiest way to do it is just to add a slice:
for i in cities[:]:
if len(i) <= 5:
cities.remove(i)
# output: ["New York", "Shanghai", "Munich"]
推荐答案
您所描述的称为参考透明的Wiki文章是一个很好的起点.
What you're describing is known as a Filter operation. You should look at the docs. The following code uses it to generate a brand new list of city names in a single line of code. Constructing a new list will prevent you from a whole class of mistakes that you can make while mutating your memory. The wiki article on Referential Transparency is a good starting point.
cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai"]
citiesWithLongNames = filter (lambda cityName: len (cityName) > 5, cities)
print (citiesWithLongNames) # => ['New York', 'Shanghai', 'Munich']
您还应该阅读所有内置函数,并且您会发现python中已经内置了很多东西,使您不必手动实现琐碎的事情.
You should also read up on all the built in functions, and you'll find that there is a bunch of stuff built into python already that keeps you from having to implement trivialities manually.
奖励:使用列表理解:
print ([city for city in cities if len (city) > 5])
比嵌套循环干净得多. :)
Much cleaner than nested loops. :)
这篇关于Python:根据长度删除列表中的字符串对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!