Python程序对列表中的元素进行计数,直到一个元素成为一个元组?
A是给定的列表。该列表具有嵌套元组。我们的任务是对列表中的元素进行计数,直到一个元素成为元组为止。在这里我们使用isinstance()函数。此函数有两个参数object和classinfo.object进行检查,并且classinfo是class,type或classandtypes的元组。如果对象是as类的实例或子类或元组的任何元素,则此函数返回true,否则返回false。
Input : A=[4, 5, 6, 10,22,33, (1, 2, 3), 11, 2, 4] Output : 6
算法
Step 1: Given a list. Step 2: Use one counter variable c which is initialized by 0. Step 3: We traverse the list and verify that encountering a tuple or not in our path of count. Step 4: If it’s true then counter will be increased by 1 otherwise false. Step 5: return c
范例程式码
# Program to count the items
# until a list is encountered a tuple
def countelement(M):
c = 0
print("RESULT ::>")
for i in M:
if isinstance(i, tuple):
break
c = c + 1
return c
# Driver Code
A = [4, 5, 6, 10,22,33, (1, 2, 3), 11, 2, 4]
print(countelement(A))输出结果
Result ::>6
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练