Python检查变量是否在列表中重复

时间:2015-07-31 01:20:49

标签: python list variables duplicates

我想知道是否有办法判断变量是否在列表中有等效变量。

/**
 * Compares two strings lexicographically.
 * The comparison is based on the Unicode value of each character in
 * the strings. The character sequence represented by this
 * {@code String} object is compared lexicographically to the
 * character sequence represented by the argument string. The result is
 * a negative integer if this {@code String} object
 * lexicographically precedes the argument string. The result is a
 * positive integer if this {@code String} object lexicographically
 * follows the argument string. The result is zero if the strings
 * are equal; 
 */

public int compareTo(String anotherString) {
    int len1 = value.length;
    int len2 = anotherString.value.length;
    int lim = Math.min(len1, len2);
    char v1[] = value;
    char v2[] = anotherString.value;

    int k = 0;
    while (k < lim) {
        char c1 = v1[k];
        char c2 = v2[k];
        if (c1 != c2) {
            return c1 - c2;
        }
        k++;
    }
    return len1 - len2;
}

有没有办法检查任何变量(a = 'hi' b = 'ji' c = 'ki' d = 'li' e = 'hi' letters = [a, b, c, d, e] )是否等于任何其他变量(a)。在这种情况下,请返回e。有没有比仅仅列出所有比较句组合更快的方法?

1 个答案:

答案 0 :(得分:4)

您可以尝试使用以下内容 -

len(letters) != len(set(letters))

当您将列表转换为set时,它会从列表中删除重复的元素,因此如果任何元素不止一次,则以字母为单位,set(letters)的长度将小于原始列表的长度,以上条件将返回True

示例/演示 -

In [9]: a = 'hi'

In [10]: b = 'ji'

In [11]: c = 'ki'

In [12]: d = 'li'

In [13]: e = 'hi'

In [14]: letters = [a, b, c, d, e]

In [15]: len(letters) != len(set(letters))
Out[15]: True

In [16]: letters = [a,b,c,d]

In [17]: len(letters) != len(set(letters))
Out[17]: False