问题描述
我正在尝试创建 self.list_my_str
与 new_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"