Python - 索引列表中的元素

[英]Python - indexing an element in a list

I am a new Python programmer and trying some stuff out. I want to create a list of strings and loop through my list to check the size of each element, if the size is greater than 5, then I will change that string into an uppercase string. I am stuck on how to access that element. Below is some of the code that I have written. Thank you in advance!


lis = ['heeeeellllooo','world','low','higggghhh']
for elem in list:
  if len(lis[elem]) > 5:

3 个解决方案



use a list comprehension with ternary operator:


In [16]: lis = ['heeeeellllooo','world','low','higggghhh']

In [17]: [x.upper() if len(x)>5 else x for x in lis] # this is a new list

Out[17]: ['HEEEEELLLLOOO', 'world', 'low', 'HIGGGGHHH']

You can also use enumerate(), enumerate returns a tuple whole first item is the index of the element and the second item is the element itself.


This method modifies the original list.


In [18]: for index,elem in enumerate(lis):
   ....:     if len(elem)>5:
   ....:         lis[index]=elem.upper()  #access element by index

In [19]: lis
Out[19]: ['HEEEEELLLLOOO', 'world', 'low', 'HIGGGGHHH']

How are lists implemented?:


Python’s lists are really variable-length arrays, not Lisp-style linked lists. The implementation uses a contiguous array of references to other objects, and keeps a pointer to this array and the array’s length in a list head structure.


This makes indexing a list a[i] an operation whose cost is independent of the size of the list or the value of the index.


When items are appended or inserted, the array of references is resized. Some cleverness is applied to improve the performance of appending items repeatedly; when the array must be grown, some extra space is allocated so the next few times don’t require an actual resize.




enumerate is very useful, if you'd like to change it in place. Try this:


for idx, elem in enumerate(lis):
    if len(elem) > 5:
        list[idx] = elem.upper()



Here is the correct way to do what you were trying using a for loop. Your code used two different variable names for the list: lis and list. The variable elem is the item in the list, not the index. To get the index, you need to use enumerate(). The solution shown by Ashwini Chaudhary is called a list comprehension and is a much better way to do this.

以下是使用for循環執行操作的正確方法。您的代碼為列表使用了兩個不同的變量名稱:lis和list。變量elem是列表中的項目,而不是索引。要獲取索引,您需要使用enumerate()。 Ashwini Chaudhary所展示的解決方案被稱為列表理解,是一種更好的方法。

for i, elem in enumerate(lis):
  if len(elem) > 5:
    lis[i] = elem.upper()



粤ICP备14056181号  © 2014-2021