如何将列表映射为dict键作为值

时间:2019-05-10 11:25:23

标签: python list dictionary collections

我有一个迭代器对象,然后在进行迭代时,它的每个项目属性都会对时间和值产生兴趣

[(point.time, point.value) for point in control_points]
[(Fraction(-1, 23), Fraction(0, 1)), (Fraction(24, 23), Fraction(100, 1))]

时间和值都是Fraction对象

现在我必须构建一个数据结构,其映射方式是第一个元组是具有in_time dict的元组,第二个元组是out_time dict的

({'in_time': "" , 'in_value': ""} , {'out_time': "", 'out_value': ""})

我还尝试过使用清单这样的方式进行其他尝试:

container = [['in_time', 'in_value'] , ['out_time', 'out_value']]

dict(zip([objects for objects in container, [(point.time, point.value) for point in contol_points]]))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required

我希望这样可以:https://stackoverflow.com/a/33737067/9567948

2 个答案:

答案 0 :(得分:0)

忽略分数并使用整数显示一种方法:

给予

control_points = [point(-1, 0), point(24, 100)]
container = [['in_time', 'in_value'] , ['out_time', 'out_value']]

通知

{ container[0][0]:control_points[0].time, container[0][1] : control_points[0].value }

给予

{'in_time': -1, 'in_value': 0}

因此,这是第一个项目。 如果您像这样枚举container

[{ c[0]:control_points[i].time, c[1] : control_points[i].value } for i,c in enumerate(container)]

您得到了:

[{'in_time': -1, 'in_value': 0}, {'out_time': 24, 'out_value': 100}]

这似乎确实在两点上,但是显示了如何进行字典压缩和枚举。

答案 1 :(得分:0)

这是我的尝试:

我使用zip中的*迭代器来访问两个列表,但是顺序不正确,因此我需要再次循环以调整顺序。

#!/usr/bin/python3

'''
Description:
Merge PDF files in to 1 pdf file in source directory.
'''

import os
import sys
try:
    from PyPDF2 import PdfFileMerger
except ImportError as missingModule:
    print('could not import PyPDF2', missingModule)


def checkType(arg):
    # check if given argument is a directory
    if os.path.isdir(arg[1]):
        # distil the source path
        arg = str(arg[1])
        # create a list with only pdf files
        pdf_files = [os.path.join(arg, f) for f in os.listdir(arg) if f.endswith('pdf')]
        src_loc = arg
        return pdf_files, src_loc
    # if arguments are pdf files, distil source folder and pdf files
    src_loc = os.path.split(sys.argv[1])[0]
    pdf_files = sys.argv[1:]
    return pdf_files, src_loc


def pdfMerger(args):
    files = args[0]
    loc = args[1]
    merger = PdfFileMerger(strict=False)
    for pdf in files:
        try:
            merger.append(open(pdf, 'rb'))
        except Exception as E:
            input(E)
    with open(loc + '/combined_pdf.pdf', 'wb') as pdf_out:
        merger.write(pdf_out)


if __name__ == '__main__':
    if len(sys.argv) < 1:
        print('Usage: Python PFM.py [directory] / [file, file, etc.]')
    pdfMerger(checkType(sys.argv))

输出: enter image description here

对于Python 2:

from fractions import Fraction
container = [['in_time', 'in_value'] , ['out_time', 'out_value']]
control_points = [(Fraction(-1, 23), Fraction(0, 1)), (Fraction(24, 23), Fraction(100, 1))]

zipped_list = list(zip(*container,*control_points))
new_dict={}
i=0
for element in zipped_list:

    while((i+3)<=len(element)):
        print([element[i]], element[i+2])
        new_dict[element[i]]=element[i+2]
        i+=1
    i=0

print(new_dict)

输出: enter image description here

相关问题