简体   繁体   English

条件列表 Python

[英]Conditional list Python

I am opening all the files present in zip, then converting the string to List and thereafter, breaking the list into 5 elements from each line.我打开 zip 中存在的所有文件,然后将字符串转换为 List,然后将列表从每行分成 5 个元素。

My code:我的代码:

with zipfile.ZipFile(dummy.zip, 'r') as mz:
    for f in mz.namelist():
        data = mz.read(f).decode('utf-8').replace("\n", '').replace("\r", ',').lstrip().rstrip().split(",") #Removing all spaces and \r from text.
        allist = [data[i:i + 5] for i in range(len(data))[::5]] #breaking list into 5 elements each

I am able to do it perfectly if all values are present but if any of the element in missing on particular line then it picks up the value from second line but I want to add NA at place of missing element.如果所有值都存在,我能够完美地做到这一点,但是如果特定行上缺少任何元素,那么它会从第二行中获取值,但我想在缺少元素的位置添加NA

File data: Dummy.zip = "File1 + File2"文件数据: Dummy.zip = "File1 + File2"

File1:文件1:

Yuli, yu@test.com, 0001, 8902
Su, su@test.com, 0002, 8903, Manager

File:2文件:2

Zaon, zn@test.com, 100, 9087, Analyst
June, ju@test.com, 278, 6078

Purpose of the code:代码的目的:

I am adding converting this list to dict, so adding keys to each entry as name, email, ext, Empid, Level我正在添加将此列表转换为 dict,因此将键添加到每个条目,如name, email, ext, Empid, Level

You can do it like this:你可以这样做:

texts = [b"Yuli, yu@test.com, 0001, 8902\r\nSu, su@test.com, 0002, 8903, Manager",
         b"Zaon, zn@test.com, 100, 9087, Analyst\r\nJune, ju@test.com, 278, 6078"]

result =[]
keys = "name,email,ext,Empid,Level".split(",")
# you do: 
# with zipfile.ZipFile(dummy.zip, 'r') as mz: 
#     for f in mz.namelist(): 
#         t = mz.read(f) here instead
# instead
for t in texts:
    for line in t.decode("utf-8").split("\n"):
        d = {k:"NA" for k in keys} # init all keys with NA
        # update with actual values
        d.update(zip(keys,(l.strip() for l in line.strip().split(","))))
        # add to result list
        result.append(d) 
print(result)

Output:输出:

[{'name': 'Yuli', 'email': 'yu@test.com', 'ext': '0001', 'Empid': '8902', 'Level': 'NA'}, 
 {'name': 'Su', 'email': 'su@test.com', 'ext': '0002', 'Empid': '8903', 'Level': 'Manager'},
 {'name': 'Zaon', 'email': 'zn@test.com', 'ext': '100', 'Empid': '9087', 'Level': 'Analyst'}, 
 {'name': 'June', 'email': 'ju@test.com', 'ext': '278', 'Empid': '6078', 'Level': 'NA'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM