Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python의 목록에서 주어진 요소를 포함하는 하위 목록 계산

<시간/>

주어진 목록의 요소는 다른 변수의 다른 문자열로 존재할 수도 있습니다. 이 기사에서 우리는 주어진 스트림이 주어진 목록에 몇 번 존재하는지 볼 것입니다.

범위 및 렌즈 포함

범위와 len 함수를 사용하여 목록의 길이를 추적합니다. 그런 다음 in 조건을 사용하여 문자열이 목록의 요소로 존재하는 횟수를 찾습니다. 0으로 초기화된 count 변수는 조건이 충족될 때마다 계속 증가합니다.

Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'Mon'

# Given list
print("Given list:\n", Alist)
print("String to check:\n", Bstring)
count = 0
for i in range(len(Alist)):
   if Bstring in Alist[i]:
      count += 1
print("Number of times the string is present in the list:\n",count)

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
String to check:
Mon
Number of times the string is present in the list:
2

합계

주어진 목록의 요소로 문자열을 일치시키기 위해 조건에서 to를 사용합니다. 그리고 마지막으로 sum 함수를 적용하여 일치 조건이 양수일 때마다 개수를 가져옵니다.

Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'Mon'
# Given list
print("Given list:\n", Alist)
print("String to check:\n", Bstring)
count = sum(Bstring in item for item in Alist)
print("Number of times the string is present in the list:\n",count)

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
String to check:
Mon
Number of times the string is present in the list:
2

카운터 및 체인 포함

itertools 및 collecitons 모듈은 문자열과 일치하는 목록의 모든 요소 수를 얻는 데 사용할 수 있는 체인 및 카운터 기능을 서비스에 제공합니다.

from itertools import chain
from collections import Counter
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'M'
# Given list
print("Given list:\n", Alist)
print("String to check:\n", Bstring)
cnt = Counter(chain.from_iterable(set(i) for i in Alist))['M']
print("Number of times the string is present in the list:\n",cnt)

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
String to check:
M
Number of times the string is present in the list:
2