-4

我有一个列表,其中包含 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,'0'] 替换输出列表,为了更好地理解,请在下面找到

例如 1 创建的输出列表:收入替换为 0

Company Mycompany| **Revenue 0**| Income 2000| employee 3000| Facilities 4000| Stock 5000

示例 2 的输出列表:将员工替换为 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

非常感谢提前

4

3 回答 3

3

如果您将输入作为列表获取,那么您可以将列表转换为这样的字典,那么您将对数据有更好的方法,但作为字典获取将是一个更好的选择

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)
于 2021-06-13T06:14:31.990 回答
1

正如评论中所说,adict是解决问题的更好的数据结构。如果你真的需要这个列表,你可以使用这样的临时字典:

example = ['Company name','Mycompany','Income','2000','employee','3000','Facilities','4000','Stock','5000']
template = ['Company name', 'Revenue', 'Income', 'employee', 'Facilities', '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使用了惰性评估。

于 2021-06-13T06:20:01.857 回答
1

您可以像这样使用字典:

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])

于 2021-06-13T06:29:51.647 回答