如何解决如何在 python 中更新动态列表?
我有一个列表,其中包含 Business = ['Company name','Mycompany',Revenue','1000','Income','2000','employee','3000','Facilities','4000 ','Stock','5000'] ,列表结构的输出如下所示:
Company Mycompany
Revenue 1000
Income 2000
employee 3000
Facilities 4000
Stock 5000
动态列表更新***
对于列表和列表中的某些项目的每次迭代 失踪
***。例如执行 1 列表更新如下:
Company Mycompany
Income 2000 #revenue is missing
employee 3000
Facilities 4000
Stock 5000
在上面的列表中,收入从列表中删除,因为公司没有收入,在第二个例子中:
Company Mycompany
Revenue 1000
Income 2000
Facilities 4000 #Employee is missing
Stock 5000
在上面的示例中,缺少 2 个员工。如何创建用 0 替换缺失值的输出列表,在示例 1 revenue is missing ,因此我必须用 ['Revenue,'0 替换输出列表'] 在它的位置,为了更好地理解,请在下面找到
为示例 1 创建的输出列表:收入替换为 0
Company Mycompany| **Revenue 0**| Income 2000| employee 3000| Facilities 4000| Stock 5000
输出列表例2:employee被0替换
Company Mycompany| Revenue 1000| Income 2000| **employee 0**| Facilities 4000| Stock 5000
如何在不改变列表结构的情况下,通过在缺失列表项上用 0 替换输出列表来实现输出列表。到目前为止我的代码:
for line in Business:
if 'Company' not in line:
Business.insert( 0,'company')
Business.insert( 1,'0')
if 'Revenue' not in line:
#got stuck here
if 'Income' not in line:
#got stuck here
if 'Employee' not in line:
#got stuck here
if 'Facilities' not in line:
#got stuck here
if 'Stock' not in line:
#got stuck here
先谢谢了
解决方法
如果您将输入作为列表获取,那么您可以将列表转换为这样的字典,那么您将有更好的数据处理方法,不过作为字典获取将是更好的选择
Business = ['Company name','Mycompany','Revenue',1000,'Income',2000,'employee',3000,'Facilities',4000,'Stock',5000]
BusinessDict = {Business[i]:Business[i+1] for i in range(0,len(Business)-1,2)}
print(BusinessDict)
,
正如评论中所说,dict
是解决问题的更好的数据结构。如果你真的需要这个列表,你可以使用这样的临时字典:
example = ['Company name','2000','3000','4000','5000']
template = ['Company name','Stock']
# build a temporary dict
exDict = dict(zip(example[::2],example[1::2]))
# work on it
result = []
for i in template:
result.append(i)
if i in exDict.keys():
result.append(exDict[i])
else:
result.append(0)
像这样创建临时字典会更有效(但对于初学者来说更难理解):
i = iter(example)
example_dict = dict(zip(i,i))
之所以有效,是因为 zip
使用了惰性求值。
你可以像这样使用字典:
d={'Company':0,'Revenue':0,'Income':0,'employee':0,'Facilities':0,'Stock':0}
given=[['Company','Mycompany'],['Income',2000],['employee',3000],['Facilities',4000],['Stock',5000]]
for i in given:
d[i[0]]=i[1]
ans=[]
for key,value in d.items():
ans.append([key,value])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。