简体   繁体   English

从输入字符串到namedtuple python 2.7

[英]From an input string to namedtuple python 2.7

Hello am a beginner on python and i want to know if ther's away to read a line and transform it to a namedtuple i will explain i have this 2 lines 您好,我是python的初学者,我想知道是否已经在外面读一行并将其转换为namedtuple,我将解释我有这2行

MARKS      CLASS      NAME       ID        
92         2          Calum      1 

For the first line : 对于第一行:

line = raw_input()
person = namedtuple('person',line)

and i made my namedtuple 我做了我的命名元组

now while i 'am reading the second line i don't know how to insert those informations in a namedtuple i tried to split it i tried all this methods but i coudn't make it 现在,当我在阅读第二行时,我不知道如何在namedtuple中插入这些信息,我试图将其拆分,我尝试了所有这些方法,但我不知道

>>> line = raw_input().split(' ')
92         2          Calum      1 
>>> line
['92', '', '', '', '', '', '', '', '', '2', '', '', '', '', '', '', 
'', '', '', 'Calum', '', '', '', '', '', '1', '']
>>> line = raw_input().split('/t')
92         2          Calum      1 
>>> line
['92         2          Calum      1 ']
>>> line = raw_input().split('        ')
92         2          Calum      1 
>>> line
['92', ' 2', '  Calum      1 ']
>>> 

Whatever what i am trying i can't have 4 arguments So please if you have any idea how can i split this string into columns help me thank you cordially 无论我在尝试什么,我都不能有4个参数。所以,如果您有任何想法,请问如何将此字符串拆分为列,请多多帮助

Just using split() will split at any whitespace characters (tabs, or multiple spaces). 仅使用split()会在任何空白字符(制表符或多个空格)处进行split() So 所以

line = raw_input()
args = line.split()

Then, because namedtuple accepts multiple arguments, not a list, you just have to unwrap the argument list, using the * operator. 然后,由于namedtuple接受多个参数,而不是列表,因此您只需要使用*运算符解开参数列表即可。

person = Person(*args)

所以根据我的答案将是使用'\\ t'而不是'/ t'

a=raw_input().split('\t')

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

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