Python列表计数及插入实例教程

Python013

Python列表计数及插入实例教程,第1张

本文实例讲述了Python列表计数及插入的用法。分享给大家供大家参考。具体如下:

代码如下:

word=['a','b','c','d','e','f','g']//首个元素为元素0,word[0]=a

a=[num1:num2]

//从num1到num2的元素(不包括元素num2)

//若为负数,则代表倒数第几个

在对list进行操作时,append 追加,word.append(elements)

elements是独立的,若为list时作为一个整体追加在word的后面,而不是延长word,

word.extend(elements)是延长,将elements包含的元素延长在word的后面insert(),插入:

代码如下:

word.insert(mum,elements)

所插入的也是也是一个整体。

希望本文所述对大家的Python程序设计有所帮助。

1.定义函数

def get_counts(sequence):

    counts={}

    for x in sequence:

        if x  in counts:

            counts[x]+= 1

         else:

              counts[x]=1

    return counts

2.定义函数(利用python标准包)

from collections import defaultdict

def get_counts2(sequence):

    counts=defaultdict(int)#所以得值均会被初始化W为0

    for x in sequence:

        if x  in counts:

            counts[x]+= 1

    return counts

3.python标准库中找到collections.Counter类

from collections improt Counter

counter(sequence)