Python에서 목록의 요소 수를 얻으려면 어떻게 해야 합니까?
내 해야 하나요?items
items = ["apple", "orange", "banana"]
# There are 3 items.
이 함수는 Python에서 내장형과 라이브러리형 모두 여러 가지 다른 유형과 함께 사용할 수 있습니다.예를 들어 다음과 같습니다.
>>> len([1, 2, 3])
3
리스트 사이즈는 어떻게 구하나요?
하려면 , 함수 「내부 함수」를 합니다.len
:
items = []
items.append("apple")
items.append("orange")
items.append("banana")
그리고 지금:
len(items)
3이 반환됩니다.
설명.
Python의 모든 것은 목록을 포함한 객체입니다.C 실장에서는 모든 오브젝트에 어떤 종류의 헤더가 있습니다.
목록 및 는 "size"라는 속성을 .ob_size
이치따라서 목록의 개체 수를 확인하는 것은 매우 빠릅니다.
리스트 「0」을 사용하지 .len
- 대신 목록을 부울 컨텍스트에 넣습니다. - 비어 있으면 False, 비어 있으면 True로 처리됩니다.
문서에서
len(s)
개체의 길이(항목 수)를 반환합니다.인수는 시퀀스(문자열, 바이트, 태플, 목록, 범위 등) 또는 컬렉션(사전, 세트, 프리즈 세트 등)입니다.
len
''은 '이행'이 됩니다.__len__
, 데이터 모델 문서:
object.__len__(self)
「」를 됩니다.
len()
를 반환해야 객체의 길이(정수 > = 0)를 반환해야 합니다. ,, 젝, a, 이, 이, 이, 이, 이, 이, 이, 이, 이, also, also, also, also, also, also, also, also, also, also, also, also, also, also__nonzero__()
2 [Python 2]의 경우]__bool__()
3와 그 Python 3]메서드를 합니다.__len__()
method는 0을 반환한다.false를 반환한다.
또 볼 수 요.__len__
의 메서드입니다.
items.__len__()
3이 반환됩니다.
에서는, 「」를 할 수 .len
)/(길이
그리고 실제로 이 정보는 위에서 설명한 모든 유형에 대해 얻을 수 있습니다.
>>> all(hasattr(cls, '__len__') for cls in (str, bytes, tuple, list,
range, dict, set, frozenset))
True
「 」를하지 주세요.len
또는 있지 않은
물론 특정 길이를 검정하려면 동일성을 검정하기만 하면 됩니다.
if len(items) == required_length:
...
하지만 제로 길이 목록 또는 그 반대에 대한 테스트에는 특별한 경우가 있습니다.이 경우 동등성을 검정하지 마십시오.
또한 다음 작업을 수행하지 마십시오.
if len(items):
...
대신 다음 작업을 수행합니다.
if items: # Then we have some items, not empty!
...
또는
if not items: # Then we have an empty list!
...
이유는 여기서 설명하지만 간단히 말하면if items
★★★★★★★★★★★★★★★★★」if not items
가독성과 퍼포먼스가 모두 향상되었습니다.
않을 수, 은 '즉각'으로 입니다.length
★★★★
class slist(list):
@property
def length(self):
return len(self)
당신은 너무 같다:사용할 수 있습니다.
>>> l = slist(range(10))
>>> l.length
10
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
객체와 하며 OOP 인 OOP, OOP 친화적인 OOP, OOP 친화적인 OOP가 .length
★★★★★★★★★★★★★★★★★★.
항상 그렇듯, 당신의 마일리지가 달라질 수 있다.
에 살고 있는데 이외에 또한 operator.length_hint(필요로 한다 파이선 3.4+)사용할 수 있다.평범한 동안list
하지만, 둘 both both both both both both both both both both both both both both both both both both bothlength_hint
수 이는 특정 도움이 될 수.「 list - iterator 」 、 「 」 、 「 」
>>> from operator import length_hint
>>> l = ["apple", "orange", "banana"]
>>> len(l)
3
>>> length_hint(l)
3
>>> list_iterator = iter(l)
>>> len(list_iterator)
TypeError: object of type 'list_iterator' has no len()
>>> length_hint(list_iterator)
3
★★★★★★★★★★★★★★★★★.length_hint
'의 경우 '유사', '유사', '유사'입니다.len
하다.
''을 하는 답변이 몇 개 __len__
을 할 때 건건모모 옳옳옳옳옳list
수 커스텀클래스는 커스텀클래스에 문제가 있을 수 있습니다len
★★★★★★★★★★★★★★★★)length_hint
의 몇 점검을 몇가지 안전 검사를 실행하다.둘 다 ('마이너스', '마이너스', '마이너스', '마이너스', '마이너스')는 허용하지 않습니다.sys.maxsize
값)을 설정합니다. 때문에 항상 할 수 있습니다.len
__len__
★★★★★★★★★★★★★★★★★★!
를 위해서, 리, 음, 음, 음, the, 음, 음, 음, 음, 음, 음, 음, 음, 다, 다, 음, 음, and, 음, 음, 음, 음, and, and, and, and, the, the, the, the, the, the, 를 사용하지 않고서도 합니다.len()
기능.PYTON에서는 이런 식으로 프로그래밍하지 않는 것이 좋은 옵션이라고는 생각하지 않지만 알고리즘을 학습하는 데 도움이 됩니다.
def count(list):
item_count = 0
for item in list[:]:
item_count += 1
return item_count
count([1,2,3,4,5])
을 사용한 (「」 「」 「」)list[:]
는 암묵적이기 때문에 옵션이기도 합니다).
새로운 프로그래머에게 여기서 배울 수 있는 교훈은 리스트 내의 아이템의 수는 어느 시점에서 카운트하지 않으면 얻을 수 없다는 것입니다.문제는 언제 그것들을 세는 것이 좋을까 하는 것입니다.를 들어sockets ()와 입니다.connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
는 요소의 길이를 계산하지 않습니다(발신측 코드에 대한 책임을 부여).주소의 길이가 전달되어 길이를 먼저 세는 절차를 생략할 수 있습니다.또 다른 옵션으로서 계산상으로는 통과된 오브젝트 내에 아이템을 추가할 때 아이템의 수를 추적하는 것이 적절할 수 있습니다.메모리 용량을 더 많이 차지한다는 점에 유의하십시오.나프툴리 케이의 답을 보세요.
메모리 공간을 늘리면서 성능을 향상시키기 위해 길이를 추적하는 예.길이가 추적되므로 len() 함수는 사용하지 않습니다.
class MyList(object):
def __init__(self):
self._data = []
self.length = 0 # length tracker that takes up memory but makes length op O(1) time
# the implicit iterator in a list class
def __iter__(self):
for elem in self._data:
yield elem
def add(self, elem):
self._data.append(elem)
self.length += 1
def remove(self, elem):
self._data.remove(elem)
self.length -= 1
mylist = MyList()
mylist.add(1)
mylist.add(2)
mylist.add(3)
print(mylist.length) # 3
mylist.remove(3)
print(mylist.length) # 2
앞서 설명한 예시와 같이 질문에 답합니다.
items = []
items.append("apple")
items.append("orange")
items.append("banana")
print items.__len__()
.len()
비단뱀
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # OUTPUT: 5
len()
이치노
my_string = "hello"
print(len(my_string)) # OUTPUT: 5
으로 말하면, ★★★★★★★★★★★★★★★★★★★★★★★★.len()
는 임의의 또는 " 크기 를 정의합니다)과 동작합니다.__len__
를 참조해 주세요.
python에는 len()이라는 함수가 내장되어 있어 이러한 상황에서 도움이 됩니다.
a=[1,2,3,4,5,6]
print(len(a)) #Here the len() function counts the number of items in the list.
출력:
>>> 6
이것은 문자열의 경우(아래)와 약간 다르게 동작합니다.
a="Hello"
print(len(a)) #Here the len() function counts the alphabets or characters in the list.
출력:
>>> 5
이는 변수(a)가 리스트가 아닌 문자열이기 때문에 문자열 내의 문자 또는 알파벳 수를 카운트한 후 출력을 출력하기 때문입니다.
목록의 요소 길이를 찾는 방법은 세 가지가 있습니다.이 세 가지 방법을 퍼포먼스 분석과 비교하겠습니다.
1: 사용방법 1: 사용방법len()
items = []
items.append("apple")
items.append("orange")
items.append("banana")
print(len(items))
출력:
3
방법 2: Naigive 카운터 방식 사용
items = []
items.append("apple")
items.append("orange")
items.append("banana")
counter = 0
for i in items:
counter = counter + 1
print(counter)
출력:
3
3: 사용방법 3: 사용방법length_hint()
items = []
items.append("apple")
items.append("orange")
items.append("banana")
from operator import length_hint
list_len_hint = length_hint(items)
print(list_len_hint)
출력:
3
분석– vs 포 perform– perform perform perform perform performlen()
»length_hint()
주의: 비교하기 위해 입력 리스트를 큰 세트로 변경하여 시차를 두고 비교합니다.
items = list(range(100000000))
# Performance Analysis
from operator import length_hint
import time
# Finding length of list
# using loop
# Initializing counter
start_time_naive = time.time()
counter = 0
for i in items:
# incrementing counter
counter = counter + 1
end_time_naive = str(time.time() - start_time_naive)
# Finding length of list
# using len()
start_time_len = time.time()
list_len = len(items)
end_time_len = str(time.time() - start_time_len)
# Finding length of list
# using length_hint()
start_time_hint = time.time()
list_len_hint = length_hint(items)
end_time_hint = str(time.time() - start_time_hint)
# Printing Times of each
print("Time taken using naive method is : " + end_time_naive)
print("Time taken using len() is : " + end_time_len)
print("Time taken using length_hint() is : " + end_time_hint)
출력:
Time taken using naive method is : 7.536813735961914
Time taken using len() is : 0.0
Time taken using length_hint() is : 0.0
결론
에 걸리는 두에 비해 매우 을 알 수 .len()
&length_hint()
사용하기에 가장 좋은 선택입니다.
의 연속 메서드는 python의 goto 메서드를 합니다.len()
a = range(1000) # range
b = 'abcdefghijklmnopqrstuvwxyz' # string
c = [10, 20, 30] # List
d = (30, 40, 50, 60, 70) # tuple
e = {11, 21, 31, 41} # set
len()
위의 모든 데이터 유형에 대해 메서드가 작동할 수 있습니다. 즉, 반복할 수 있기 때문입니다.
all_var = [a, b, c, d, e] # All variables are stored to a list
for var in all_var:
print(len(var))
인 len()
def len(iterable, /):
total = 0
for i in iterable:
total += 1
return total
에 in in의 len()
실제로 동작하고 있는 것은, C 의 실장입니다.
static PyObject *
builtin_len(PyObject *module, PyObject *obj)
/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
{
Py_ssize_t res;
res = PyObject_Size(obj);
if (res < 0) {
assert(PyErr_Occurred());
return NULL;
}
return PyLong_FromSsize_t(res);
}
Py_ssize_t
는 객체의 최대 길이입니다.는 객체의 크기를 반환하는 함수입니다.개체의 크기를 확인할 수 없는 경우 -1을 반환합니다.이 경우 다음 코드블록이 실행됩니다.
if (res < 0) {
assert(PyErr_Occurred());
return NULL;
}
그 결과 예외가 발생합니다.그렇지 않으면 이 코드 블록이 실행됩니다.
return PyLong_FromSsize_t(res);
res
은 ,입니다.C
Python ", Python "으로됩니다.int
(Python 2에는 정수를 저장하기 위한 두 가지 유형이 있기 때문에 C 코드에서는 여전히 "Long"으로 불리고 있습니다)이 반환되었습니다.
간단히 사용하다
len(list_name)
또는 다음과 같은 펑션링크를 만들 수 있습니다.
def count(list):
item_count = 0
for item in list[:]:
item_count += 1
return item_count
Python에서 목록 길이를 찾는 방법
List in Python은 주문 및 변경이 가능한 다양한 유형의 데이터를 저장하기 위해 구현되며 중복된 값을 가질 수도 있습니다.여기서 Python은 목록의 길이를 찾는 세 가지 방법이 있습니다.
- 렌()
리스트내의 요소의 합계수를 취득하기 위한 built-in 함수 len()입니다.len() 메서드는 목록을 제공할 수 있는 인수를 사용하여 지정된 목록의 길이를 반환합니다.Python에서 목록 길이를 찾는 가장 편리한 방법입니다.
#Finding length of list by using len() method
list_example = [1, 2, 3, 4, 5,6,7,8,9]
print("The length of list is: ", len(list_example))
The output will be:
Output:
The length of list is: 9
- 순진한 방법
목록의 길이는 for loop을 사용하여 쉽게 찾을 수 있으며 이 방법을 Naigive 메서드라고 합니다.요약하면 다음과 같습니다.
먼저 카운터 변수를 선언하고 0으로 초기화합니다.
루프를 사용하여 모든 데이터 요소를 통과하고 모든 요소를 발견한 후 카운터 변수를 1씩 증가시킵니다.
이제 배열의 길이가 카운터 변수에 저장되고 목록 내의 요소 수를 나타냅니다.
#Finding length of list by using Naive method
#Initializing list
list_example = [1, 2, 3, 4, 5,6,7,8,9]
print("The list is: ", str(list_example))
#finding length of list using loop
counter = 0
for i in list_example:
counter = counter + 1
print ("Length of list using Naive Method is: ", str(counter))
- length_param()
이 메서드는 연산자 클래스에서 정의되며 목록의 길이를 정의할 수도 있습니다.
#Using Length_hint() Method
from operator import length_hint
list_len_1 = [1, 2, 3, 5, 6, 'PickupBrain']
list_len_hint = length_hint(list_len_1)
print(list_len_hint)
len(), Naigive 메서드 및 lenght_list 메서드의 성능 테스트
이 시간 분석은 모든 메서드를 실행하는 데 걸리는 시간을 이해하는 데 도움이 되며 다른 메서드를 선택하는 데 도움이 됩니다.
#Code for Performance Analysis
from operator import length_hint
import time
#define list
list_example = [1, 2, 3, 4, 5,6,7,8,9]
print("The list is: ", list_example)
# Using Naive method & loop to find length of list
# Initializing counter
start_naive_time = time.time()
counter = 0
for i in list_example:
counter = counter + 1
end_naive_time = float(time.time() - start_naive_time)
# Using len() method
start_len_time = time.time()
list_len = len(list_example)
end_len_time = float(time.time()- start_len_time)
# Using length_hint() method
start_hint_time = time.time()
list_hint = length_hint(list_example)
end_hint_time = float(time.time()- start_hint_time)
#Printing time for each method
print("Time taken by Naive Method: ", end_naive_time)
print("Time taken by Length_hint() Method: ", end_len_time)
print("Time taken by len() Method: ", end_hint_time)
The output will be this:
Output:
The list is: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Time taken by Naive Method: 3.0994415283203125e-06
Time taken by Length_hint() Method: 4.76837158203125e-07
Time taken by len() Method: 1.1920928955078125e-06
결론: 소요시간은 Naigive Method >> len()> length_hint()입니다.
언급URL : https://stackoverflow.com/questions/1712227/how-do-i-get-the-number-of-elements-in-a-list-in-python
'itsource' 카테고리의 다른 글
LAST_INSERT_를 사용하여 여러 테이블에 삽입PDO준비명세서내 아이디 (0) | 2022.09.04 |
---|---|
JavaScript에서 날짜/시간을 빼는 방법 (0) | 2022.09.04 |
64비트 정수를 16진수로 인쇄하는 방법 (0) | 2022.09.03 |
휴지 상태 시퀀스가 존재하지 않습니다. (0) | 2022.09.03 |
Https Connection Android (0) | 2022.09.03 |