파이썬에서 목록을 어떻게 되돌릴 수 있습니까?
파이썬에서 다음을 어떻게 할 수 있습니까?
array = [0, 10, 20, 40]
for (i = array.length() - 1; i >= 0; i--)
배열의 요소가 필요하지만 끝에서 시작까지.
reversed
이 기능을 다음과 같이 사용할 수 있습니다 .
>>> array=[0,10,20,40]
>>> for i in reversed(array):
... print(i)
참고 reversed(...)
목록을 반환하지 않습니다. 을 사용하여 반전 된 목록을 얻을 수 있습니다 list(reversed(array))
.
>>> L = [0,10,20,40]
>>> L[::-1]
[40, 20, 10, 0]
확장 된 슬라이스 구문은 릴리스 용 Python 새 기능 항목에 잘 설명되어 있습니다.2.3.5
코멘트의 특별한 요청에 의해 이것은 가장 최근의 슬라이스 문서 입니다.
>>> L = [0,10,20,40]
>>> L.reverse()
>>> L
[40, 20, 10, 0]
또는
>>> L[::-1]
[40, 20, 10, 0]
이것은 목록을 복제하는 것입니다.
L = [0,10,20,40]
p = L[::-1] # Here p will be having reversed list
이것은 목록을 제자리에서 되 돌리는 것입니다.
L.reverse() # Here L will be reversed in-place (no new list made)
파이썬에서 목록을 뒤집는 가장 좋은 방법은 다음과 같습니다.
a = [1,2,3,4]
a = a[::-1]
print(a)
>>> [4,3,2,1]
작업이 완료되었으며 이제 목록이 반전되었습니다.
동일한 목록을 반전하려면 다음을 사용하십시오.
array.reverse()
반전 된 목록을 다른 목록에 할당하려면 다음을 사용하십시오.
newArray = array[::-1]
슬라이싱 (예 : array = array [::-1])을 사용하는 것은 깔끔한 트릭이며 매우 Pythonic이지만 초보자에게는 약간 모호 할 수 있습니다. reverse () 메서드를 사용하는 것은 읽기 쉬우므로 일상적인 코딩에 좋은 방법입니다.
그러나 인터뷰 질문에서와 같이 목록을 뒤집어 야하는 경우 이와 같은 기본 제공 방법을 사용하지 못할 수 있습니다. 면접관은 Python 지식의 깊이보다는 문제에 접근하는 방법을 살펴볼 것입니다. 알고리즘 접근 방식이 필요합니다. 클래식 스왑을 사용하는 다음 예제는이를 수행하는 한 가지 방법 일 수 있습니다.
def reverse_in_place(lst): # Declare a function
size = len(lst) # Get the length of the sequence
hiindex = size - 1
its = size/2 # Number of iterations required
for i in xrange(0, its): # i is the low index pointer
temp = lst[hiindex] # Perform a classic swap
lst[hiindex] = lst[i]
lst[i] = temp
hiindex -= 1 # Decrement the high index pointer
print "Done!"
# Now test it!!
array = [2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654]
print array # Print the original sequence
reverse_in_place(array) # Call the function passing the list
print array # Print reversed list
**The result:**
[2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654]
Done!
[654, 124, 24, 7, 1, 65, 60, 32, 27, 25, 19, 12, 9, 8, 5, 2]
이것은 튜플이나 문자열 시퀀스에서는 작동하지 않습니다. 왜냐하면 문자열과 튜플은 불변이기 때문입니다. 즉, 요소를 변경하기 위해 쓸 수 없기 때문입니다.
(다른 제안과는 달리) l.reverse()
파이썬 3과 2에서 긴 목록을 되 돌리는 가장 빠른 방법이라는 것을 발견했습니다. 다른 사람들이 이러한 타이밍을 복제 할 수 있는지 알고 싶습니다.
l[::-1]
목록을 반전하기 전에 복사하기 때문에 더 느릴 수 있습니다. list()
이터레이터 주위 에 호출을 reversed(l)
추가하면 약간의 오버 헤드가 추가되어야합니다. 물론 목록이나 반복자의 복사본을 원하면 각각의 방법을 사용하지만 목록을 뒤집고 싶다면 l.reverse()
가장 빠른 방법 인 것 같습니다.
기능
def rev_list1(l):
return l[::-1]
def rev_list2(l):
return list(reversed(l))
def rev_list3(l):
l.reverse()
return l
명부
l = list(range(1000000))
Python 3.5 타이밍
timeit(lambda: rev_list1(l), number=1000)
# 6.48
timeit(lambda: rev_list2(l), number=1000)
# 7.13
timeit(lambda: rev_list3(l), number=1000)
# 0.44
Python 2.7 타이밍
timeit(lambda: rev_list1(l), number=1000)
# 6.76
timeit(lambda: rev_list2(l), number=1000)
# 9.18
timeit(lambda: rev_list3(l), number=1000)
# 0.46
for x in array[::-1]:
do stuff
>>> list1 = [1,2,3]
>>> reversed_list = list(reversed(list1))
>>> reversed_list
>>> [3, 2, 1]
array=[0,10,20,40]
for e in reversed(array):
print e
reversed (array)를 사용하는 것이 가장 좋은 방법입니다.
>>> array = [1,2,3,4]
>>> for item in reversed(array):
>>> print item
내장 된 .NET Framework를 사용하지 않고이를 구현하는 방법을 이해해야합니다 reversed
.
def reverse(a):
midpoint = len(a)/2
for item in a[:midpoint]:
otherside = (len(a) - a.index(item)) - 1
temp = a[otherside]
a[otherside] = a[a.index(item)]
a[a.index(item)] = temp
return a
O (N) 시간이 걸립니다.
당신이 다른 변수에 반대 목록의 요소를 저장하려면, 당신은 사용할 수 있습니다 revArray = array[::-1]
또는 revArray = list(reversed(array))
.
그러나 첫 번째 변형은 약간 더 빠릅니다.
z = range(1000000)
startTimeTic = time.time()
y = z[::-1]
print("Time: %s s" % (time.time() - startTimeTic))
f = range(1000000)
startTimeTic = time.time()
g = list(reversed(f))
print("Time: %s s" % (time.time() - startTimeTic))
산출:
Time: 0.00489711761475 s
Time: 0.00609302520752 s
조직 가치 :
파이썬에서는 목록의 순서도 sort 로 조작 할 수 있으며 숫자 / 알파벳 순서로 변수를 구성 할 수 있습니다 .
일시적으로 :
print(sorted(my_list))
영구적 인:
my_list.sort(), print(my_list)
"reverse = True" 플래그를 사용하여 정렬 할 수 있습니다 .
print(sorted(my_list, reverse=True))
또는
my_list.sort(reverse=True), print(my_list)
조직없이
값을 정렬하지 않고 값을 반대로하기 만하면됩니다. 그런 다음 다음과 같이 할 수 있습니다.
print(list(reversed(my_list)))
** 숫자는 목록 순서에서 알파벳보다 우선합니다. Python 가치의 구성은 훌륭합니다.
목록 이해력 사용 :
[array[n] for n in range(len(array)-1, -1, -1)]
Strictly speaking, the question is not how to return a list in reverse but rather how to reverse a list with an example list name array
.
To reverse a list named "array"
use array.reverse()
.
The incredibly useful slice method as described can also be used to reverse a list in place by defining the list as a sliced modification of itself using array = array[::-1]
.
def reverse(text):
output = []
for i in range(len(text)-1, -1, -1):
output.append(text[i])
return output
You can also use the bitwise complement of the array index to step through the array in reverse:
>>> array = [0, 10, 20, 40]
>>> [array[~i] for i, _ in enumerate(array)]
[40, 20, 10, 0]
Whatever you do, don't do it this way.
Using some logic
Using some old school logic to practice for interviews.
Swapping numbers front to back. Using two pointers
index[0] and index[last]
def reverse(array):
n = array
first = 0
last = len(array) - 1
while first < last:
holder = n[first]
n[first] = n[last]
n[last] = holder
first += 1
last -= 1
return n
input -> [-1 ,1, 2, 3, 4, 5, 6]
output -> [6, 1, 2, 3, 4, 5, -1]
The most direct translation of your requirement into Python is this for
statement:
for i in xrange(len(array) - 1, -1, -1):
print i, array[i]
This is rather cryptic but may be useful.
def reverse(my_list):
L = len(my_list)
for i in range(L/2):
my_list[i], my_list[L-i - 1] = my_list[L-i-1], my_list[i]
return my_list
You could always treat the list like a stack just popping the elements off the top of the stack from the back end of the list. That way you take advantage of first in last out characteristics of a stack. Of course you are consuming the 1st array. I do like this method in that it's pretty intuitive in that you see one list being consumed from the back end while the other is being built from the front end.
>>> l = [1,2,3,4,5,6]; nl=[]
>>> while l:
nl.append(l.pop())
>>> print nl
[6, 5, 4, 3, 2, 1]
def reverse(text):
lst=[]
for i in range(0,len(text)):
lst.append(text[(len(text)-1)-i])
return ''.join(lst)
print reverse('reversed')
list_data = [1,2,3,4,5]
l = len(list_data)
i=l+1
rev_data = []
while l>0:
j=i-l
l-=1
rev_data.append(list_data[-j])
print "After Rev:- %s" %rev_data
Reversing in-place by switching references of opposite indices:
>>> l = [1,2,3,4,5,6,7]
>>> for i in range(len(l)//2):
... l[i], l[-1-i] = l[-1-i], l[i]
...
>>> l
[7, 6, 5, 4, 3, 2, 1]
With minimum amount of built-in functions, assuming it's interview settings
array = [1, 2, 3, 4, 5, 6,7, 8]
inverse = [] #create container for inverse array
length = len(array) #to iterate later, returns 8
counter = length - 1 #because the 8th element is on position 7 (as python starts from 0)
for i in range(length):
inverse.append(array[counter])
counter -= 1
print(inverse)
use
print(reversed(list_name))
>>> L = [1, 2, 3, 4]
>>> L = [L[-i] for i in range(1, len(L) + 1)]
>>> L
[4, 3, 2, 1]
>>> l = [1, 2, 3, 4, 5]
>>> print(reduce(lambda acc, x: [x] + acc, l, []))
[5, 4, 3, 2, 1]
This class uses Python magic methods and iterators for reversing, and reverses a list:
class Reverse(object):
""" Builds a reverse method using magic methods """
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
REV_INSTANCE = Reverse([0, 10, 20, 40])
iter(REV_INSTANCE)
rev_list = []
for i in REV_INSTANCE:
rev_list.append(i)
print(rev_list)
Output
[40, 20, 10, 0]
참고URL : https://stackoverflow.com/questions/3940128/how-can-i-reverse-a-list-in-python
'program tip' 카테고리의 다른 글
HTTPS URL이 암호화됩니까? (0) | 2020.09.28 |
---|---|
다시 그리기 위해 캔버스를 지우는 방법 (0) | 2020.09.28 |
extern을 사용하여 소스 파일간에 변수를 공유하려면 어떻게해야합니까? (0) | 2020.09.28 |
Git : 마스터에서 준비되지 않은 / 커밋되지 않은 변경 사항에서 분기 만들기 (0) | 2020.09.28 |
Java에서 배열을 목록으로 변환 (0) | 2020.09.28 |