2017-10-15 69 views
1

我有一个列表,它看起来像这样:Python 3 - 列表到词典。排序的话

['Data', '2017-10-12', 'Nr', 'lekcji', '6', 'Nauczyciel', 'Name', 'Nothing', 'Rodzaj', 'sprawdzian', 'Przedmiot', 'Math', 'Opis', 'This', 'is', 'just', 'a', 'test.', 'Data', 'dodania', '2017-10-01', '18:12:31'] 

而且我希望把它转换要列出一些关键字。这里是我想要得到的结果:

{'Data': '2017-10-12', 'Nr lekcji': '6', 'Nauczyciel': 'Name Nothing', 'Rodzaj': 'sprawdzian', 'Przedmiot': 'Math', 'Opis': 'This is just a test.', 'Data dodania': '2017-10-01 18:21:32'} 

这可能吗?感谢帮助!

编辑

基本字符串:

Data 
2017-10-12 


Nr lekcji 
6 


Nauczyciel 
Name Nothing 


Rodzaj 
sprawdzian 


Przedmiot 
Math 


Opis 
This is just a test. 


Data dodania 

             2017-10-01 18:12:31          
+3

如何决定何时组项目,并按照不将它们分组? –

+1

你是如何获得第一份名单的?它看起来像是来自某个地方,并被过分地分割在空白处...... –

+0

是的,这是可能的,但要制作一段代码片段,您可以重复更多次,我们需要了解您是如何获得列表的。 –

回答

2

下面是一个例子:

string = """Data 
2017-10-12 


Nr lekcji 
6 


Nauczyciel 
Name Nothing 


Rodzaj 
sprawdzian 


Przedmiot 
Math 


Opis 
This is just a test. 


Data dodania 

             2017-10-01 18:12:31 """ 

# Clean the input data by splitting by row and removing blanks 
clean = [i.strip() for i in string.split("\n") if i] 

# Assume the data is in pairs and group them in key,pair by using index 
# and index+1 in [0,2,4,6...] 
d = {clean[ind]:clean[ind+1] for ind in range(0,len(clean),2)} 

print(d) 

返回:

{'Data': '2017-10-12', 
'Data dodania': '2017-10-01 18:12:31', 
'Nauczyciel': 'Name Nothing', 
'Nr lekcji': '6', 
'Opis': 'This is just a test.', 
'Przedmiot': 'Math', 
'Rodzaj': 'sprawdzian'} 
1

您可以使用下面的代码来创建一个字典来自您的原始文本:

# Defined multiline variable with your raw datat 
text = """Data 
2017-10-12 


Nr lekcji 
6 


Nauczyciel 
Name Nothing 


Rodzaj 
sprawdzian 


Przedmiot 
Math 


Opis 
This is just a test. 


Data dodania 

            2017-10-01 18:12:31 """ 

# Clean the data to strip empty lines and unnecessary spaces 
cleaned = [line.strip() for line in text.split('\n') if line.strip() != ''] 

# Create a dictionary from the stripped list where the value of each key is 
# the item in the list which comes after the key 
myDict = dict(zip(cleaned[0::2], cleaned[1::2])) 

,其结果是:

>>> myDict 
{'Nr lekcji': '6', 
'Nauczyciel': 'Name Nothing', 
'Przedmiot': 'Math', 
'Rodzaj': 'sprawdzian', 
'Opis': 'This is just a test.', 
'Data': '2017-10-12', 
'Data dodania': '2017-10-01 18:12:31'} 
0

也许它不是一个干净的解决方案,但可能是有用的。

with open('file.txt') as myfile: 
    lines = map(lambda e: e.strip(), filter(lambda e: len(e) > 0, myfile.read().split('\n'))) 
    # or in 3 lines 
    # raw_lines = myfile.read().split('\n') 
    # nonzero_length_lines = filter(lambda e: len(e) > 0, raw_lines) 
    # lines = map(lambda e: e.strip(), nonzero_length_lines) 
    h = {} 
    i = 0 
    while i<len(lines)-1: 
     h[lines[i]] = lines[i+1] 
     i+=2 
    print(h) 

https://repl.it/MeO5