如何在python中获取列表列表的String的第n个元素?

时间:2018-04-11 15:10:04

标签: python

我的txt文件是这样的。

[0, "we break dance not hearts by Short Stack is my ringtone.... i LOVE that !!!.....\n"]
[1, "I want to write a . I think I will.\n"]
[2, "@va_stress broke my twitter..\n"]
[3, "\" "Y must people insist on talking about stupid politics on the comments of a bubblegum pop . Sorry\n"]
[4, "aww great  "Picture to burn"\n"]

我有一些想要访问每个数组的第二个元素的代码。当我使用Get the nth element from the inner list of a list of lists in Python中的代码时,它会给每个字符但不是整个字符串。

为获得第二个元素制作循环的最佳方法是什么?

我的代码是这样的。

这些推文都在推文[]列表中。

cluster = []
for idx, cls in enumerate(km.labels_):
    if cls == 1:
        # printing cluster 2 data.
        # print tweets from the tweets array. like the entire line. But I 
        # want to get the String here not the entire line.
        print tweets[idx]
        cluster.append(tweets[idx])

这里,idx元素用于获取特定查询。因此推文[idx]将打印文本文件中的特定查询,但它正在打印整行,如[2,“@va_stress打破了我的推特.. \ n”],我只想要字符串元素。

3 个答案:

答案 0 :(得分:0)

我猜你想要的是每个列表中的字符串。我假设您已经有一个列表参数列表与您的文本文件中的每个列表。 因此你可以应用它来获取值。

list_of_strings = filter(lambda x:x[1], list_of_lists)

答案 1 :(得分:0)

您可以尝试以下任何一种方法:

data=[[0, "we break dance not hearts by Short Stack is my ringtone.... i LOVE that !!!.....\n"],
[1, "I want to write a . I think I will.\n"],
[2, "@va_stress broke my twitter..\n"],
[3, "\" "Y must people insist on talking about stupid politics on the comments of a bubblegum pop . Sorry\n"],
[4, "aww great  "Picture to burn"\n"]]


print(list(map(lambda x:x[1].strip(),data)))

print([i[1].strip() for i in data])

输出:

['we break dance not hearts by Short Stack is my ringtone.... i LOVE that !!!.....', 'I want to write a . I think I will.', '@va_stress broke my twitter..', '" "Y must people insist on talking about stupid politics on the comments of a bubblegum pop . Sorry', 'aww great  "Picture to burn"']

答案 2 :(得分:0)

试试这个:

data=eval('['+(open('file.txt').read().replace('\n', ', ')[:-2])+']')
result=[]
for i in data:
    data.append(i[1])

最后3行非常明显,但这是第一行:

  1. open('file.txt').read()打开文件并获取内容
  2. .replace('\n', ', ')[:-2],替换换行符,除了最后一行,以便将其格式化为列表。如果最后一行没有以换行符结尾,请跳过[:-2]
  3. '['+...+']'添加[]以获取更多格式列表。
  4. data=eval(...) make会创建列表并将其分配给data
  5. 以下是最后一行的内容:

    1. 创建空列表并将其分配给result
    2. i已为data中的每个值分配以下行:
    3. data中每个列表的第二个值附加到result