如何返回每个唯一字符串的元组列表及其给定字符串列表的计数?

时间:2016-09-14 00:13:17

标签: python python-3.x

不知道从哪里开始...... item()给出了一个字典,我不希望这样。

我想说我需要遍历清单......

请有人给我一些提示,以便我可以开始使用!

编辑:

#grad4_left img {
    height: 100%;
    width: 100%;
    border-radius: 10px 0px 0px 10px;
}

#grad4_right {
    z-index: inherit;
    height: 700px;
    background-color: #F1EEF7;
    top: 705px;
    width: 50%;
    left: 50%;
    text-align: center;
    font-size: 80px;
    line-height: 40px;
    color: #4A4A4A;
}

.grad#grad4_left {
    z-index: inherit;
    height: 700px;
    background-color: black;
    top: 705px;
    right: 50%;
    color: #4A4A4A;
    width: 50%;
}

输出:

count_of_names(names)

    counts_of_names(['John', John', 'Catherine', 'John', 'Christopher', 'Catherine']' 

3 个答案:

答案 0 :(得分:0)

您可以使用collections.Counter()来实现此目的。例如:

>>> x = [1,2,3,4,1,1,2,3]
>>> my_list = Counter(x).items()
>>> my_list
[(1, 3), (2, 2), (3, 2), (4, 1)]

# In order to sort the list base based on value of tuple at index `1` and then index `0`
>>> sorted(my_list, key=lambda x: (x[1], x[0]))
[(4, 1), (2, 2), (3, 2), (1, 3)]

答案 1 :(得分:0)

这是一个很难的方法:

x = [1,3,2,5,6,6,3,2]
x_tuple = []

y = set(x)

for i in y:
    x_tuple.append((i,x.count(i)))

print(x_tuple)

答案 2 :(得分:0)

使用var elementOne = $('#wrapper1')[0].childNodes[2]; $(elementOne).wrap("<span style='color: red;'>"); 和列表理解:

set