如何创建两个列表的并集然后迭代它

How to create a union of two lists and then iterate it

我正在尝试创建 self.list_my_strnew_list 的并集,我想迭代这个新创建的列表。我目前的尝试:

class Stringuri(): 
    list_my_str = []

    def __init__(self, my_str):
        self.my_str = my_str

    def strtolist(self):
        len_my_str = len(self.my_str)
        for i in range(0, len_my_str):
            self.list_my_str.append(self.my_str[i])
        return self.list_my_str

    def reversestr(self):
        new_list = self.list_my_str.copy()
        new_list.reverse()
        return new_list

    reunion = self.list_my_str.extend(new_list)

    def __iter__(self):
        all_series = []
        for i in reunion:
            all_series.append(i)
        return StringIterabil(all_series)

class StringIterabil():
    def __init__(self, series):
        self.series = series
        pass

    def __iter__(self):
        return self

    def __next__(self):
        if not self.series:
            raise StopIteration
        else:
            return self.series.pop(0)

测试代码:

a = Stringuri('Ana are mere')
print(a.strtolist())
print("-----------")
print(a.reversestr())
print("-----------")
for i in a:
    print(i)

我是 Python 类 的初学者,欢迎任何有助于我更好地理解 类 的书籍、视频或其他东西。

如果您想要两个列表的并集,并且不希望相同的项目出现两次,最好的方法是使用集合。

list1 = ['a', 'b', 'c', 'e']
list2 = ['d', 'e', 'f', 'g']
union_of_lists = list(set(list1).union(set(list2)))

有用的提示:每当您修改 python 中的对象时,例如使用 append() 或 extend() 修改原始对象,因此将输出保存在新变量中将为您提供 NoneType 对象。

# alternative way to combine two lists without removing duplicates
[i for i in list1 or list2]

您要实现的目标称为字符串连接,您可以在两个 str:

上使用 + 运算符来实现
str_1 = "Hello, "
str_2 = "world!"
str_3 = str_1 + str_2
# str_3 = "Hello, world!"

您还可以就地连接 str+=:

str_1 = "Hello, "
str_1 += "world!"
# str_1 = "Hello, world!"

如果要反转str,可以使用字符串切片:

s_1 = "abcd"
s_2 = s_2[::-1]
# s_2 = "dcba"