错误是因为只能将列表(而不是“非类型”)连接到列表

2024-09-28 19:06:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想反转Jamies_列表和Drews列表,应该先在列表中,然后附加这两个列表,我想返回完整的列表

def combine_lists(list1, list2):
  # Generate a new list containing the elements of list2
  # Followed by the elements of list1 in reverse order
  return(list2+list1.reverse())
    
Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"]
Drews_list = ["Mike", "Carol", "Greg", "Marcia"]

print(combine_lists(Jamies_list, Drews_list))

Tags: ofthe列表newdefelementsgeneratelists
2条回答

reverse()是Python编程语言中的一种内置方法,在适当的位置反转列表中的对象

也可以使用print(list1.reverse())进行检查。它不会打印任何内容

因此建议使用return list2 + list1[::-1]

.reverse()是一种就地操作。它不会返回反向列表,而是返回None

使用sorted(list1, reverse=True)

def combine_lists(list1, list2):
  # Generate a new list containing the elements of list2
  # Followed by the elements of list1 in reverse order
  return(list2+sorted(list1, reverse=True))
    
Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"]
Drews_list = ["Mike", "Carol", "Greg", "Marcia"]

print(combine_lists(Jamies_list, Drews_list))

否则

def combine_lists(list1, list2):
  # Generate a new list containing the elements of list2
  # Followed by the elements of list1 in reverse order
  list1.reverse()
  return(list2+list1)
    
Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"]
Drews_list = ["Mike", "Carol", "Greg", "Marcia"]

print(combine_lists(Jamies_list, Drews_list))

否则

def combine_lists(list1, list2):
  # Generate a new list containing the elements of list2
  # Followed by the elements of list1 in reverse order
  return list2 + list1[::-1]
    
Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"]
Drews_list = ["Mike", "Carol", "Greg", "Marcia"]

print(combine_lists(Jamies_list, Drews_list))

相关问题 更多 >