【发布时间】:2020-06-03 04:45:24
【问题描述】:
我正在使用字符串和方法进行 Python 练习。 (我知道有一些额外的打印语句和 cmets。)目标是返回列表中的所有其他项目。所以对于第一个例子,目标是返回 - # 应该是 ['a', 'c', 'e', 'g']
我很挣扎,因为我不知道为什么我的代码不会从列表中删除“b”。我错过了什么? .
我查看了以下特定的 StackOverflow 问题。 (加上其他)
- Need help on List of Strings
- How to remove an element from a list by index
- Remove empty strings from a list of strings
- Difference between del, remove and pop on lists
def skip_elements(elements):
L_elements = len(elements)
for x in elements:
print("This is L_elements: " , L_elements)
#print(x)
if (L_elements % 2 == 0):
elements.pop((L_elements-1))
print(elements)
if (L_elements == 2):
print("This is L_elements: " , L_elements, "Should equal 2")
L_elements = L_elements - 1
return elements
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []
【问题讨论】:
-
您可以使用列表理解来保留每个偶数索引。
[x for x in list if list.index(x) % 2 == 0] -
@alec,请不要使用
list作为名字。 -
对不起,我认为这样的语句会更清晰,而不是使用另一个变量名。正如斯蒂芬所说,“列表”是内置函数的名称,不应用作变量名。
标签: python python-3.x string list methods