本文介绍了重新开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我是第一次尝试了解正则表达式,并且非常有用,这对于获得一个例子很有帮助。我有一个旧的(呃)脚本,带有以下

任务 - 需要一个我复制粘贴的字符串,并且格式相同:

hi all,

I''m trying to understand regex for the first time, and it would be very
helpful to get an example. I have an old(er) script with the following
task - takes a string I copy-pasted and wich always has the same format:



我想知道有没有更好的方法来使用re模块?

perheps甚至避免这个for循环?


谢谢!


I was wondering is there a better way to do it using re module?
perheps even avoiding this for loop?

thanks!

推荐答案




这是一种在没有RE的情况下做同样事情的方法:


data =''黄色帽子\t2 \蓝色衬衫\ t1 \白色袜子\t4 \绿色

pants\ t1 \\\
nlue bag \t4 \tNice香水\t3 \\\
Wri st watch \t7 \tMobile

phone \t4 \ n无线电话!\t2 \t建筑工具\t3 \ nOne为

money \\ t7t \tTwo for show \t4''


data2 = data.replace(" \ n"," \t")。s​​plit(") \t")

result1 = dict(zip(data2 [:: 2],map(int,data2 [1 :: 2])))


O如果你想变轻:


来自itertools import imap,izip,islice

data2 = data.replace(" \\\
" ,\t,分割(\t)

strings = islice(data2,0,len(data),2)

数字= islice(data2,1,len(数据),2)

result2 = dict(izip(strings,imap(int,numbers)))


再见,

bearophile



This is a way to do the same thing without REs:

data = ''Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen
pants\t1\nBlue bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile
phone\t4\nWireless cord!\t2\tBuilding tools\t3\nOne for the
money\t7\tTwo for the show\t4''

data2 = data.replace("\n","\t").split("\t")
result1 = dict( zip(data2[::2], map(int, data2[1::2])) )

O if you want to be light:

from itertools import imap, izip, islice
data2 = data.replace("\n","\t").split("\t")
strings = islice(data2, 0, len(data), 2)
numbers = islice(data2, 1, len(data), 2)
result2 = dict( izip(strings, imap(int, numbers)) )

Bye,
bearophile




我想知道有没有更好的方法来使用re模块?
perheps甚至避免这个for循环?

谢谢!


I was wondering is there a better way to do it using re module?
perheps even avoiding this for loop?

thanks!









这可能必须是:


strings = islice(data2,0,len(data2),2)

numbers = islice(data2 ,1,len(data2),2)


对不起,

。熊市



This probably has to be:

strings = islice(data2, 0, len(data2), 2)
numbers = islice(data2, 1, len(data2), 2)

Sorry,
bearophile


这篇关于重新开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-10 13:06