简体   繁体   English

pythonic将字符串拆分为两个列表的方法

[英]pythonic way to split string into two lists

I have a lot of files with string pairs looking like: 我有很多字符串对的文件看起来像:

first_string~second_string first_string〜second_string

The first part is what to change and the second, to what change the first part. 第一部分是改变什么,第二部分是改变第一部分。

These are regular expressions and I run my app with these collections to apply all modifications to dirty tv schedule listings for more than a hundred channels. 这些是正则表达式,我运行我的应用程序与这些集合,以应用所有修改脏电视时间表列表超过一百个频道。 I did it before with C# but now I am reworking it in Python. 我之前用C#做过,但现在我正在用Python重新编写它。

Let's imagine I have a text file with many strings each on its own line that look like find_this~change_to_this . 让我们假设我有一个文本文件,其中每个字符串都有自己的行,看起来像find_this~change_to_this I need to get two lists. 我需要得到两个清单。 First will contain all find strings and the second will contain all change strings. 第一个将包含所有查找字符串,第二个将包含所有更改字符串。

Let's imagine, I have 120 such pairs. 让我们想象一下,我有120对这样的对。 Now I divide these pairs into two lists, each has size of 120 items. 现在我将这些对分成两个列表,每个列表大小为120个项目。 One has finds, the other - changes. 一个人发现,另一个 - 发生变化。 Now I can get both strings by some index, for example, 57, and it will give me 57th item from both lists, so I get a right change string for any find string. 现在我可以通过一些索引得到两个字符串,例如57,它将从两个列表中给出第57项,所以我得到任何查找字符串的正确更改字符串。 I found some variants, but not sure which one is better. 我找到了一些变体,但不确定哪一个更好。

What is the pythonic to split a collection of strings like this: 什么是pythonic来分割这样的字符串集合:

first_string~second_string

Using that input to split it into two lists where first list contains items before ~ and the second one - after. 使用该输入将其拆分为两个列表,其中第一个列表包含〜之前的项目,第二个列表包含之后的项目。

x = ["c~d", "e~f", "g~h"]
a, b = zip(*(s.split("~") for s in x))
print a
print b

prints 版画

('c', 'e', 'g')
('d', 'f', 'h')

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

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