简体   繁体   English

如何在Python中拆分字符串列表

[英]How to split a list of strings in Python

Say I have a list of strings like so: 说我有一个像这样的字符串列表:

list = ["Jan 1", "John Smith", "Jan 2", "Bobby Johnson"]

How can I split them into two separate lists like this? 我如何将它们分成两个单独的列表? My teacher mentioned something about indexing but didn't do a very good job of explaining it 我的老师提到了有关索引的一些内容,但在解释方面做得不好

li1 = ["Jan 1", "John Smith"]
li2 = ["Jan 2", "Bobby Johnson"]

Well, use list slicing: 好吧,使用列表切片:

li1 = my_list[:2]
li2 = my_list[2:]

BTW, don't use the name list for a variable because you are shadowing the built-in list type. 顺便说一句,不要使用变量的名称list ,因为您正在隐藏内置list类型。

If your list is longer than just two entries you could do this: 如果您的列表超过两个条目,则可以执行以下操作:

zip(list[0::2],list[1::2])

Output: 输出:

[('Jan 1', 'John Smith'), ('Jan 2', 'Bobby Johnson')]

One of ways to do make it work with lists of arbitrary length in a clean and simple manner: 一种使它以干净简单的方式与任意长度的列表一起使用的方法之一:

all_lists = (list[x:x+2] for x in range(0, len(list), 2))

And then you can access new lists by: 然后,您可以通过以下方式访问新列表:

li1 = all_lists[0]
li2 = all_lists[1]

Or just iterate through them: 或者只是遍历它们:

for new_list in all_lists:
    print(new_list)

As all_lists is a generator (in both Python 2.X and 3.X) it will also work on large chunks of data. 由于all_lists是一个生成器(在Python 2.X和3.X中都是如此),因此它也可以处理大量数据。

If the length of the list isn't always going to be the same, or known from the start you can do this: 如果列表的长度不总是相同,或者一开始就知道,则可以执行以下操作:

original_list = [YOUR ORIGINAL LIST]

A = [:len(original_list)/2]
B = [len(original_list)/2:]

A will be the first half and B will be the second half. A将是上半部分,B将是下半部分。

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

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