Home  >  Article  >  Backend Development  >  Python analysis of methods for flipping elements in a given list

Python analysis of methods for flipping elements in a given list

不言
不言Original
2018-04-27 11:49:531928browse

This article mainly introduces Python's method of flipping elements in a given list. It analyzes the implementation techniques of Python's two flipping operations based on slicing and traversing output for list elements based on examples. It has certain reference value and is needed. Friends can refer to the following

The example of this article describes the method of flipping elements in a given list in Python. Share it with everyone for your reference, the details are as follows:

Question

Given a list, flip the elements in it and output them in reverse order

The method is very simple , here are two methods. The first and simplest method is the slicing operation for the list. The following is the specific implementation


#!usr/bin/env python
#encoding:utf-8
'''''
__Author__:沂水寒城
功能:翻转列表
'''
def inverse_list1(num_list):
  '''''
  翻转列表
  '''
  print num_list[::-1]
def inverse_list2(num_list):
  '''''
  翻转列表
  '''
  n = len(num_list)
  for i in xrange(n / 2):
    t = num_list[i]
    num_list[i] = num_list[n-1-i]
    num_list[n-1-i] = t
  print num_list
if __name__ == '__main__':
  print "脚本之家测试结果:"
  num_list=[1,2,3,4,5,6,7,8,9,0]
  inverse_list1(num_list)
  inverse_list2(num_list)


The results are as follows:

Script House test results:
[0, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[0, 9 , 8, 7, 6, 5, 4, 3, 2, 1]

The screenshot of the running results is as follows:

Comparison from the above example It can be seen that the slice-based operation is the simplest flip method.

Related recommendations:

Python method of reading file names to generate a list

Python method of reading all images in a specified folder


The above is the detailed content of Python analysis of methods for flipping elements in a given list. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn