简体   繁体   English

Python 列表 - 在新列表中复制列表值

[英]Python lists - Copy list values in new list

This is what I am trying:这就是我正在尝试的:

I have a text file with few lines of input in the format - parameter value我有一个文本文件,其中有几行输入格式 - parameter value

This text file is read line by line and parameters & values are taken into as list elements.这个文本文件被逐行读取,参数和值被作为列表元素。

a = []
for line in fileinput.input():
    a.append((line.strip()).split(' '))
print a

Output:输出:

[['parameter1': 'value1'], ['parameter2': 'value2'], ['parameter3': 'value3']]

I am now trying to move these values - value1, value2, value3, & so on - in to a new list.我现在试图将这些值 - value1、value2、value3 等 - 移到新列表中。

I can't figure this out.我想不通。 copy function will copy the full list.复制功能将复制完整列表。 Do I use loops to iterate through these values and append to new list?我是否使用循环遍历这些值并附加到新列表? Is it possible to add these values directly to new list while reading from the text file..?从文本文件读取时,是否可以将这些值直接添加到新列表中..?

You can do that with a list comprehension:您可以使用列表理解来做到这一点:

new_a = [sub[1] for sub in a]

You could also do this:你也可以这样做:

import operator

new_a = list(map(operator.itemgetter(1), a))

An equivalent of that is to use a lambda function:相当于使用lambda函数:

new_a = list(map(lambda x: x[1], a))

As mentioned in a comment, you could also do this:正如评论中提到的,你也可以这样做:

new_a = [value for parameter, value in a]

That last will throw an error if any of the lists in a is not of length two.这最后将抛出一个错误,如果任何在列表中的a是长度为二不是。 That could be a good thing or a bad thing depending on what you want.这可能是好事也可能是坏事,这取决于你想要什么。

You could also just use your for loop only add just the second element:您也可以只使用for循环只添加第二个元素:

a = []
for line in fileinput.input():
    a.append(line.split(' ')[1])
print a

I must confess, I didn't even notice that until I saw flaschbier's answer.我必须承认,直到我看到 flaschbier 的回答我才注意到这一点。

b.append(line.split(' ')[1])

will append only the value from each line to another list b you have prepared before the loop.将追加仅value从每行到另一个列表b你循环之前准备。

The output of the program from the question will be问题的程序输出将是

[['parameter1', 'value1'], ['parameter2', 'value2'], ['parameter3', 'value3']]

btw...顺便提一句...

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

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