Python程序在列表中的第一个 j 之前出现 i
给定一个列表,任务是编写一个Python程序来计算第 i个元素在第 j个元素第一次出现之前的出现次数。
例子:
Input : test_list = [4, 5, 6, 4, 1, 4, 8, 5, 4, 3, 4, 9], i, j = 4, 8
Output : 3
Explanation : 4 occurrs 3 times before 8 occurs.
Input : test_list = [4, 5, 6, 4, 1, 4, 8, 5, 4, 3, 4, 9], i, j = 5, 8
Output : 1
Explanation : 5 occurrs 1 time before 8 occurs.
方法#1:使用循环。
在这种情况下,我们在遇到 i 时增加 counter 并在发生任何 j 时停止,即从循环中中断。
Python3
# Python3 code to demonstrate working of
# Occurrences of i before first j
# Using loop
# initializing Matrix
test_list = [4, 5, 6, 4, 1, 4, 8, 5, 4, 3, 4, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing i, j
i, j = 4, 8
res = 0
for ele in test_list:
# breaking on 1st j
if ele == j:
break
# counting i till 1st j
if ele == i:
res += 1
# printing result
print("Number of i's till 1st j : " + str(res))
Python3
# Python3 code to demonstrate working of
# Occurrences of i before first j
# Using index() + slicing + count()
# initializing Matrix
test_list = [4, 5, 6, 4, 1, 4, 8, 5, 4, 3, 4, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing i, j
i, j = 4, 8
# getting index
jidx = test_list.index(j)
# slicing list
temp = test_list[:jidx]
# getting count
res = temp.count(i)
# printing result
print("Number of i's till 1st j : " + str(res))
输出:
The original list is : [4, 5, 6, 4, 1, 4, 8, 5, 4, 3, 4, 9]
Number of i's till 1st j : 3
方法#2:使用index() +切片+ count()
在此,我们执行获取 j 的索引的任务,然后将列表切片到那里,count() 用于获取切片列表中 i 的计数以获得所需的结果。
蟒蛇3
# Python3 code to demonstrate working of
# Occurrences of i before first j
# Using index() + slicing + count()
# initializing Matrix
test_list = [4, 5, 6, 4, 1, 4, 8, 5, 4, 3, 4, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing i, j
i, j = 4, 8
# getting index
jidx = test_list.index(j)
# slicing list
temp = test_list[:jidx]
# getting count
res = temp.count(i)
# printing result
print("Number of i's till 1st j : " + str(res))
输出:
The original list is : [4, 5, 6, 4, 1, 4, 8, 5, 4, 3, 4, 9]
Number of i's till 1st j : 3