深度阅读

How to get unique values from a list in Python

作者
作者
2023年08月22日
更新时间
17.74 分钟
阅读时间
0
阅读量

To get unique string values from a list in Python, you can use a set to remove duplicates. Here’s an example:

my_list = ['hello', 'world', 'hello', 'python', 'world']
unique_strings = set(my_list)
print(unique_strings)  # Output: {'python', 'world', 'hello'}

In this example, we first define a list my_list containing a mix of string elements, including some duplicates. We then use the set() function to remove duplicates and create a new set unique_strings containing only the unique string elements. Finally, we print the resulting set unique_strings, which contains only the unique string elements from the original list.

Note that using a set to remove duplicates will change the order of the original list. If you need to maintain the original order of the list, you can use a for loop and an if statement to check if each element is already in a new list. Here’s an example:

my_list = ['hello', 'world', 'hello', 'python', 'world']
unique_strings = []
for element in my_list:
    if element not in unique_strings and type(element) == str:
        unique_strings.append(element)
print(unique_strings)  # Output: ['hello', 'world', 'python']

Here, we first define an empty list unique_strings that will store only the unique string elements. We use a for loop to iterate over the elements of the original list. On each iteration, we check if the current element is not already in the unique_strings list (to remove duplicates) and if it is a string using an if statement. If it meets both conditions, we append it to the unique_strings list using the append() method. Finally, we print the resulting unique_strings list, which contains only the unique string elements from the original list in their original order.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。