在python

时间:2015-11-23 01:34:26

标签: python list

我有一个包含n个元素的python列表,其中n-1相同而1不相同。我需要找到不同元素的位置。

例如:考虑一个python列表[1,1,1,2,1,1]。 我需要在列表中找出2的位置。

我可以使用for循环来比较连续元素,然后再使用两个for循环来将这些元素与其他元素进行比较。但是有没有更有效的方法来实现它,或者是我不知道的内置函数?

3 个答案:

答案 0 :(得分:1)

从中set制作一个set,然后在list中计算index()个元素'的出现次数,并在其中找到唯一元素的l = [1,1,1,2,1,1] a,b = set(l) if l.count(a) == 1: unique = l.index(a) else: unique = l.index(b)

>>> unique
3

结果:

var myData = '[{"amt":"500","tag":"travel","date":"2015-11-23"},{"amt":"3750","tag":"rent","date":"2015-11-23"},{"amt":"500","tag":"food","date":"2015-11-23"},{"amt":"500","tag":"rent","date":"2015-11-23"},{"amt":"500","tag":"food","date":"2015-11-23"},{"amt":"3750","tag":"rent","date":"2015-11-23"},{"amt":"30","tag":"drinks","date":"2015-11-23"}]';

var myObj = generateTmpObj(JSON.parse(myData));

var tmpArray = [['Tag', 'Amount']];
    tmpArray = generate_array_for_DataTable(myObj);

google.setOnLoadCallback(drawChart(tmpArray));

function generateTmpObj(data) {
    var tmpObj = {};
    for(var i = 0; i < data.length; i++) {
       if (tmpObj[data[i].tag]) {
           tmpObj[data[i].tag] += parseInt(data[i].amt);
       } else {
           tmpObj[data[i].tag] = parseInt(data[i].amt);
       }
    }
    return tmpObj;
 }

 function generate_array_for_DataTable(data) {
    for (var prop in data) {
        tmpArray.push([prop, data[prop]]); 
    }
    return tmpArray;
 }

function drawChart(data) {
    var data = google.visualization.arrayToDataTable(data);

    var options = {
      title: 'My Pie Chart'
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
  }

答案 1 :(得分:1)

您可以使用Counter,例如:

from collections import Counter

a = [1, 1, 1, 1, 2, 3, 3, 1, 1]
c = Counter(a)
for item, count in c.iteritems():
    if count == 1:
        print a.index(item)

这将打印出4,列表中的索引为2

答案 2 :(得分:0)

这是一种稍微有效的方式(仅列出一次而不是TigerhawkT3's answer中的三次),但不是很干净:

def find_distinct_index(a):
    if len(a) < 3: raise ValueError("Too short of a list")
    if a[0] == a[1]:
        # it's neither the first nor the second element, so return
        # the index of the leftmost element that is *not* equal to 
        # the first element
        for i, el in enumerate(a):
            if el != a[0]: return i
        raise ValueError("List had no distinct elements")
    else:
        # it's either the first or the second. use the third to figure
        # out which to return
        return a[1] if a[0] == a[2] else a[0]