목록을 위한 필수 Python 3 코드
21272 단어 programmingpythoninterviewbeginners
인터뷰에서 목록 및 벡터에 대한 필수 코드
edA‑qa mort‑ora‑y ・ 1919년 3월 1일 ・ 7분 읽기
#coding
#beginners
#career
#interview
이 구문에는 많은 변형이 있지만 한 가지 방법만 알고 있으면 괜찮습니다. 대부분의 경우 Pythonic 방식을 찾으려고 노력했습니다. 이것을 치트 시트로 사용할 수 있습니다.
기초
# Create a list
mylist = []
# Add an element to the front or back
mylist.append( "abc" )
mylist.insert( 0, "def" )
# Pop element off front or back
end = mylist.pop()
start = mylist.pop( 0 )
# Forward iterate over elements
for item in mylist:
print( item )
# Get the length of list
len( mylist )
# Test if empty
if not mylist:
print( "list is empty" )
위치 기반 운영
# Get item at location
mylist[2]
# Insert an item at location
mylist.insert( 3, "abc" )
# Remove an item from location
del mylist[2]
# Replace/Assign item at location
mylist[1] = "def"
정렬 및 검색
# Find an item
if item in mylist:
index = mylist.index(item)
# Using `index` and error handling
try:
index = mylist.index( 'abc' )
except ValueError:
index = None
# Using `next` and filtering
next((x for x in mylist if x == 'ghif'), None)
# Find and remove an item
if item in mylist:
mylist.remove( item )
# with error handling
try:
mylist.remove( item )
except ValueError:
pass
# Find last matching item
# Index of found item, or None
next( (index for index in reversed( range( len( mylist ) ) ) if mylist[index] == item), None)
# Alternately, reverse list and use "Find an item", but that copies the list
revlist = mylist[::-1]
if item in revlist:
index = revlist.index( item )
# Sort by natural order
# in-place sort
mylist.sort()
# Sort with custom comparator
mylist = [ ('a', 10), ('b', 7), ('c',13), ('d',1) ]
# sort by a key (sub-element
mylist.sort( key = lambda item: item[1] )
# custom comparator
def compare_fn( a, b ):
return some_cond( a, b )
mylist.sort( key = functools.cmp_to_key( compare_fn ) )
세그먼트 조작
# Split the list at arbitrary location
tail_of_list = mylist[2:]
head_of_list = mylist[:2]
# Multiple splits based on a match
mylist = ['a', 'b', 'c', 'd', 'b', 'e']
[list(y) for x, y in itertools.groupby( mylist, lambda z: z == 'b') if not x]
# Clear the list
mylist.clear()
# Remove segment
# delete from position 1 up to, but excluding position 3
del mylist[1:3]
# Concatenate lists
mylist + other_list
# Insert list at location
# list slicing replaces the segment of list with another one, here we replace a zero-length slice
mylist[1:1] = other_list
# Get a sublist
# sublist starting at position 1 up to, but excluding, position 3
mylist[1:3]
더 많은 반복
# Backward
for item in reversed( mylist ):
print( item )
# Partial segment iteration
# using itertools.islice avoids copying the list (which is what would happen if you used a slice)
for item in itertools.islice( mylist, 1, 4 ):
print( item )
# Skipping elements
# step from element 1 to 6 (exclusive) by 2
for item in itertools.islice( mylist, 1, 6, 2 ):
print( item )
창조
# Create from a static list of items
mylist = [ 'abc', 'def', 'ghi']
# Create a range of numbers
# a list of numbers from 10..20 (exclusive)
numbers = list( range( 10, 20 ) )
데이터 조작
# Mapping
[number * 10 for number in numbers]
# Filtering
[number for number in numbers if number % 2 == 0]
# Fold / Reduce
# Summing up numbers using builtin add
functools.reduce( operator.add, numbers )
# Joining string representations of items
functools.reduce( lambda left,right: str( left ) + '/' + str( right ), mylist )
# Zip
# the zip function produces a list of tuples
zip( lista, listb )
# to alternate items into one list use reduce
functools.reduce( operator.add, zip( lista, listb ) )
고급의
# Swap elements at two locations
mylist[3], mylist[5] = mylist[5], mylist[3]
# Reserve capacity
# Python lists do not expose capacity
# Replace content in a list
mylist[:] = other_list
# Compare two lists
lista == listb
# Search a sorted list
# bisect_left/bisect_right work with sorted lists,
# find an item ndx using bisect_left, finds the left-most item
ndx = bisect_left( numbers, 4 )
if ndx != len(numbers) and numbers[ndx] == 4
print( "Found at {}".format(ndx) )
# Iterators
# Manually stepping through an iterator
myiter = iter( mylist )
while True:
try:
n = next( myiter )
print(n)
except StopIteration:
break
# Multiple iterators at the same time
itera = iter( lista )
iterb = iter( listb )
while True:
try:
a = next( itera )
b = next( iterb )
print( a, b )
except StopIteration:
break
훌륭한 프로그래머가 되기 위한 더 많은 방법을 배우고 싶습니까? 내 책 읽기What is Programming? . 저는 사람들, 소프트웨어가 존재하는 이유, 그 소프트웨어의 중심에 있는 코드, 키보드 뒤의 사람인 당신을 봅니다.
Reference
이 문제에 관하여(목록을 위한 필수 Python 3 코드), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/mortoray/essential-python-3-code-for-lists-45f0텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)