Python 3.x 仅使用循环将列表插入另一个列表:
我正在使用python的当前版本。我需要返回列表1的副本,并在索引指示的位置插入列表2,即如果索引值为2,则将列表2插入列表1的位置2。我只能使用for/while循环、range函数和list_name.append(value)方法,列表不能切片。因此,如果list1 list1=boom list2=red,索引值=2,我如何返回一个新的list=boredom?到目前为止,我有:Python 3.x 仅使用循环将列表插入另一个列表:,python-3.x,Python 3.x,我正在使用python的当前版本。我需要返回列表1的副本,并在索引指示的位置插入列表2,即如果索引值为2,则将列表2插入列表1的位置2。我只能使用for/while循环、range函数和list_name.append(value)方法,列表不能切片。因此,如果list1 list1=boom list2=red,索引值=2,我如何返回一个新的list=boredom?到目前为止,我有: list1 = ['b','o','o','m'] list2 = ['r','e','d'] index
list1 = ['b','o','o','m']
list2 = ['r','e','d']
index = 2
new_list = []
if index > len(list1):
new_list = list1 + list2
print (new_list)
if index <= 0:
new_list = list2 + list1
print (new_list)
list1=['b','o','o','m']
列表2=['r'、'e'、'd']
指数=2
新列表=[]
如果索引>len(列表1):
新列表=列表1+列表2
打印(新列表)
如果索引一旦点击索引,使用内部循环来追加列表2中的每个元素:
for ind, ele in enumerate(list1):
# we are at the index'th element in list1 so start adding all
# elements from list2
if ind == index:
for ele2 in list2:
new_list.append(ele2)
# make sure to always append list1 elements too
new_list.append(ele)
print(new_list)
['b', 'o', 'r', 'e', 'd', 'o', 'm']
如果必须使用范围,请将枚举替换为范围:
new_list = []
for ind in range(len(list1)):
if ind == index:
for ele2 in list2:
new_list.append(ele2)
new_list.append(list1[ind])
print(new_list)
['b', 'o', 'r', 'e', 'd', 'o', 'm']
或不使用ifs使用扩展和删除(如果允许):
new_list = []
for i in range(index):
new_list.append(list1[i])
list1.remove(list1[i])
new_list.extend(list2)
new_list.extend(list1)
一旦我们点击索引就追加意味着将从正确的索引插入元素,列表1中的元素必须总是在if检查之后追加 Padriac的替代方法-对
循环使用三种:
list1 = ['b','o','o','m']
list2 = ['r','e','d']
n = 2
new_list = []
for i in range(n): # append list1 until insert point
new_list.append(list1[i])
for i in list2: # append all of list2
new_list.append(i)
for i in range(n, len(list1)): # append the remainder of list1
new_list.append(list1[i])
看看我写的这段代码。
检查所使用的状态。我希望它能回答你的问题
email = ("rishavmani.bhurtel@gmail.com")
email_split = list(email)
email_len = len(email)
email_uname_len = email_len - 10
email_uname = []
a = 0
while (a < email_uname_len):
email_uname[a:email_uname_len] = email_split[a:email_uname_len]
a = a + 1
uname = ''.join(email_uname)
uname = uname.replace(".", " ")
print("Possible User's Name can be = %s " %(uname))
email=(“rishavmani。bhurtel@gmail.com")
电子邮件分割=列表(电子邮件)
email_len=len(电子邮件)
email\u uname\u len=email\u len-10
电子邮件地址_uname=[]
a=0
而(a
也不能使用枚举或字典-只能使用if/elif语句,while/for循环、.append()和范围函数-非常令人沮丧和受限-还有其他建议吗?@SMF-01,第二种方法满足所有这些条件。不用担心,您可以用while循环替换范围,并使用类似的逻辑,但是没有其他更简单的方法来处理您所遇到的限制have@Padraic嗯-我试过另一个版本-请注意-它长了一行-但是,如果
s:p,则不使用任何,因此字面上仅为while/for
,范围
和列表。追加
:)