简体   繁体   English

如何在列表中找到Python中具有相同值的元素?

[英]How can I find elements in a list that have same value in Python?

My question is how can I find strings in a list that have the same number of characters if my list is... 我的问题是,如果我的列表是......我如何在列表中找到具有相同字符数的字符串...

myList = ["Hello", "How","are", "you"]

and I want it to return the strings that are of value 3 我希望它返回值为3的字符串

example from above list... 以上列表中的示例...

["How","are","you"]

This is what I've tried... 这就是我试过的......

def listNum(myList, x):
    for i in range(len(myList)):
        if i == x:
            return(i)



myList = ["Hello", "How","are", "you"]
x = 3
listNum(myList, x)

Your function is off because you are comparing the list index to the value you are trying to match with i == x . 您的函数已关闭,因为您正在将列表索引与您尝试与i == x匹配的值进行比较。 You want to use myList[i] == x . 你想使用myList[i] == x But it seems you actually want to check the length, so len(myList[i]) == x . 但看起来你真的想检查长度,所以len(myList[i]) == x

However, I prefer iterating over the actual elements in a loop (or list comprehension as noted in comments by Joran Beasley). 但是,我更喜欢迭代循环中的实际元素(或者如Joran Beasley的评论中所述的列表理解)。 You also mentioned that you wanted to check if for string of certain length, so you can also add a check for the object type: 您还提到要检查是否为特定长度的字符串 ,因此您还可以添加对象类型的检查:

def listNum(myList, x):
    return [item for item in myList if type(item) is str and len(item) == x]

Use the setdefault() method. 使用setdefault()方法。 This solution should give you a dictionary of all the word lengths mapped to their respective words 此解决方案应该为您提供映射到其各自单词的所有单词长度的字典

CODE

myList = ["Hello", "How","are", "you"]

dict1 = {}
for ele in myList:
    key = len(ele)
    dict1.setdefault(key, [])
    dict1[key].append(ele)

OUTPUT OUTPUT

I guess this is the output you are trying to achieve. 我想这是你想要实现的输出。

>>> print(dict1)
{5: ['Hello'], 3: ['How', 'are', 'you']}

You can use this to query the dictionary and get the words corresponding to their word lengths. 您可以使用它来查询字典并获取与其字长相对应的单词。 For eg dict1[5] would return 'hello' 例如dict1[5]会返回'hello'

If you are planning to use it for further enhancement i suggest you make dict in one loop then you can easily retrieve that for any number of characters. 如果您打算使用它进行进一步增强,我建议您在一个循环中创建dict,然后您可以轻松地检索任意数量的字符。 if you search for x=3 or 4 each time you have to go through your list. 如果每次必须查看列表时搜索x = 3或4。 rather then that make dict with one loop. 而是用一个循环制作字典。

myList = ["Hello", "How","are", "you"]

data = {}
for i in myList:
    if len(i) in data:
        data[len(i)].append(i)
    else:
        data[len(i)] = [i]

# print(data)

x = 3
print(data[x])

output: 输出:

['How', 'are', 'you']

I believe you can use Python filter function here. 我相信你可以在这里使用Python filter功能。

# list
myList = ["Hello", "How","are", "you"]

# function that examines each element in an array and returns it if True
def filterData(item):
    if(len(item) == 3):
        return True
    else:
        return False

# filter function that takes 'function-to-run' and an array
filtered = filter(filterData, myList)

# result
print('The filtered strings are:')
for item in filtered:
    print(item)

Hope it helped. 希望它有所帮助。 Cheers! 干杯!

You can use the function groupby() with a sorted list: 您可以将函数groupby()与排序列表一起使用:

from itertools import groupby

myList = ["Hello", "How", "are", "you"]

f = lambda x: len(x)
l = sorted(myList, key=f)
r = {k: list(g) for k, g in groupby(l, key=f)}
# {3: ['How', 'are', 'you'], 5: ['Hello']}
r[3]
# ['How', 'are', 'you']

Try this code. 试试这个代码。

Code

def func_same_length(array,index):
    res = [array[i] for i in range(0,len(array)) if len(array[index]) == len(array[i]) and i!=index]
    return res



myList = ["Hello", "How", "are", "you"]
resSet = set()
for index in range(0,len(myList)):
    res = func_same_length(myList,index)
    for i in res:
        resSet.add(i)

print(resSet)

Output 产量

{'How', 'are', 'you'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 for 循环查找列表中具有相同值的元素之间的元素 - Find elements in list that is between elements with that have the same value using a for loop 如何在python中相同的元组列表中找到所有元素? - How do i find all the elements in a list of tuples that are same in python? 如何在具有相同元素的列表中找到子列表的索引? - How can I find the indices of the sublists in my list with the same elements? 如何查找列表中是否连续有2个相同值的元素? - How to find if there are 2 elements of same value consecutively in a list? 如何从每个键的键列表中初始化 python 中的字典以具有相同的初始值? - How can I initialize a dictionary in python from a list of keys for each key to have the same initial value? 如果具有相同的值,我如何对列表进行分组? - How can I group a list if have same value? 如何调整列表以使某些元素位于同一索引上? - How can I adjust the list to have some elements positioned on the same index? 如何从列表中查找和删除具有特定模式的元素? - How can I find and remove elements that have a specific pattern from a list? 如何在 Python 中查找恰好出现 2 的列表元素的索引 - How to find index of elements of a list that have occurrance of exactly 2 in Python Python,我怎样才能找到这些元素的总和? - Python, how I can find sum of this elements?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM