5

请问有没有自动定义生成列表的方法

 3 years ago
source link: https://www.v2ex.com/t/798953
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Python

请问有没有自动定义生成列表的方法

  alfina · 1 天前 · 533 次点击
最近刚接触 python,想请问下:

在处理一堆 list 类型数据的时候,有没有办法在不提前定义出空 list 的时候,根据需求凭空创建出一堆名字自动生成出来的 list 呢?

比方说我搜到的所谓的列表生成往往是这样的
# 举例:a = [1,2,3] b = [ 'A' , 'B' , 'C' ] 生成 ls = [ 'A1' , 'B2' , 'C3 ']
a = [1, 2, 3]
b = ['A', 'B', 'C']
ls = []
# 获取 0,1,2,用作原始列表的下标,索引原始列表的元素,以便于操作
for i in range(0, 3):
# int 和 str 不能直接拼接,先将 int 转为 str
x = b[i] + str(a[i])
ls.append(x)
print(ls)

在提前定义出 ls = []后,利用 for 之类的功能往里面塞东西.
而当我有很多列表时,想凭借任意两个列表的组合创造出一个新列表的时候有没有方法不去手动创建,而是写一个方法像是:
def create_new_list(list1,list2)

新列表的名字命名规则像是: "newlist_from_"+list1+list2
这里的 list1 与 list2 就是 def create_new_list(list1,list2)里面两个 list 的名字
然后这个新列表内包含像是 newlist_from_list1+list2 = [(list1[0]+list2[0]),(list1[1]+list2[1])...]

第一次问这种抽象编程问题不太好表达 不知道能不能让人理解

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK