在python中使用list

tvokkenx  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(93)
transactions_clean = []
for transac in daily_transactions_split:
    transaction_clean = []
    for tran in transac:
        transaction_clean.append(tran.replace("\n", "").strip(" "))
    transactions_clean.append(transaction_clean)

有没有人能解释一下作者为什么要创建transaction_clean = []??而他/她可以直接将剥离的值附加到transactions_clean

disho6za

disho6za1#

作者正在创建列表列表:

[['this', 'is'], ['a', 'list'], ['of', 'lists']]

注意,使用列表解析来创建子列表会更简洁:

transactions_clean = []
for transac in daily_transactions_split:
    transaction_clean = [tran.replace("\n", "").strip(" ") for tran in transac]
    transactions_clean.append(transaction_clean)

如果你想得到真正的幻想,加倍的理解:

transactions_clean = [[tran.replace("\n", "").strip(" ") for tran in transac] for transac in daily_transactions_split]

相关问题