我有一个如下所示的有效负载-
1,a1,21,31,b1
2,a2,22,32,b2
3,,23,33,b3
4,a4,,,b4
并尝试从此字符串中获取第二列,并将其放入列表中。
预期输出:
[a1,a2,a4]
我尝试了下面的代码,但未获得所需的输出-
ListPayload = []
for line in ((payload.text).splitlines()):
ListPayload.append(line)
这样做,我得到如下输出-
['1,a1,21,31,b1','2,a2,22,32,b2','3,,23,33,b3','4,a4,,,b4']
并使用下面的代码获取第二列-
filteredList =[]
for i in range(len(ListPayload)):
filteredList.append(ListPayload[i].split(",")[1])
然后我在下面使用它来获取所需的输出
result = [x for x in filteredList if x]
print(result)
是否有比这更好的方法来获得所需的输出?
答案 0 :(得分:1)
代替写作
ListPayload = []
for line in ((payload.text).splitlines()):
ListPayload.append(line)
您可以简单地写:
lines = payload.text.splitlines()
(请注意,我已将“ ListPayload”重命名为“ lines”,但这可能取决于个人喜好)
而不是:
filterList =[]
for i in range(len(ListPayload)):
filterList.append(ListPayload[i].split(",")[1])
您可以写:
result = [line.split(",")[1] for line in lines]
您可以过滤如下结果:
result = [line.split(",")[1] for line in lines if line.split(",")[1]]
但是在这种情况下,我希望有一个简单的循环(避免以上述形式多次调用split()
)。
完整示例
将所有内容放在一起将产生以下代码:
result = []
lines = payload.text.split()
for line in lines:
columns = line.split(',')
if columns[1]:
result.append(columns[1])
print(repr(result))
这将输出:
['a1', 'a2', 'a4']
答案 1 :(得分:1)
您可以通过以下方法轻松完成此操作:
txt = '''1,a1,21,31,b1
2,a2,22,32,b2
3,,23,33,b3
4,a4,,,b4'''
result = [line.split(',')[1] for line in txt.splitlines() if line.split(',')[1]]
print(result)
输出:
['a1', 'a2', 'a4']
尽管这是一个简短的解决方案,但是从技术上讲,以下方法更快,因为它每行仅调用一次split
:
txt = '''1,a1,21,31,b1
2,a2,22,32,b2
3,,23,33,b3
4,a4,,,b4'''
result = []
for line in txt.splitlines():
desired = line.split(',')[1]
if desired:
result.append(desired)
print(result)
答案 2 :(得分:1)
尝试一下:
payload = '''1,a1,21,31,b1
2,a2,22,32,b2
3,,23,33,b3
4,a4,,,b4'''
col = 1 # you can extract any column
[line.split(',')[col] for line in ((payload).splitlines()) if line.split(',')[col]]
Output:
## ['a1', 'a2', 'a4']