从Python列表中删除值

发布于 2024-09-12 01:13:29 字数 351 浏览 3 评论 0原文

我有一个由空格分隔的单行名称和值的大文件:

name1 name2 name3....

长长的名称列表后面是与名称对应的值列表。值可以是 0-4 或 na。我想要做的是合并数据文件,并在值为 na 时删除所有名称和值。

例如,此文件中名称的最后一行如下所示:

namenexttolast nameonemore namethelast 0 na 2

我想要以下输出:

namenexttolast namethelast 0 2

我该怎么做这是使用Python吗?

I have a large file of names and values on a single line separated by a space:

name1 name2 name3....

Following the long list of names is a list of values corresponding to the names. The values can be 0-4 or na. What I want to do is consolidate the data file and remove all the names and and values when the value is na.

For instance, the final line of name in this file is like so:

namenexttolast nameonemore namethelast 0 na 2

I would like the following output:

namenexttolast namethelast 0 2

How would I do this using Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

情话难免假 2024-09-19 01:13:29

假设您将名称读入一个列表,然后将值读入另一个列表。一旦有了 namesvalues 列表,您就可以执行以下操作:

result = [n for n, v in zip(names, values) if v != 'na']

result 现在是值不是“na”的所有名称的列表”。

Let's say you read the names into one list, then the values into another. Once you have a names and values list, you can do something like:

result = [n for n, v in zip(names, values) if v != 'na']

result is now a list of all names whose value is not "na".

想挽留 2024-09-19 01:13:29
s = "name1 name2 name3 v1 na v2"
s = s.split(' ')
names = s[:len(s)/2]
values = s[len(s)/2:]

names_and_values = zip(names, values)
names, values = [], []
[(names.append(n) or values.append(v)) for n, v in names_and_values if v != "na"]
names.extend(values)

print ' '.join(names)

更新

根据 Paul 的建议进行了小幅改进。我确信列表理解相当不Pythonic,因为它利用了 list.append 返回 None 的事实,因此两个 append 表达式都将是评估后,将构建一个 None 值列表并立即丢弃。

s = "name1 name2 name3 v1 na v2"
s = s.split(' ')
names = s[:len(s)/2]
values = s[len(s)/2:]

names_and_values = zip(names, values)
names, values = [], []
[(names.append(n) or values.append(v)) for n, v in names_and_values if v != "na"]
names.extend(values)

print ' '.join(names)

Update

Minor improvement after suggestion from Paul. I'm sure the list comprehension is fairly unpythonic, as it leverages the fact that list.append returns None, so both append expressions will be evaluated and a list of None values will be constructed and immediately thrown away.

ゃ懵逼小萝莉 2024-09-19 01:13:29

我同意 Justin 的观点,认为使用 zip 是个好主意。问题是如何将数据放入两个不同的列表中。这是一个应该可以正常工作的提案。

reader = open('input.txt')
writer = open('output.txt', 'w')
names, nums = [], []
row = reader.read().split(' ')
x = len(row)/2
for (a, b) in [(n, v) for n, v in zip(row[:x], row[x:]) if v!='na']:
    names.append(a)
    nums.append(b)
writer.write(' '.join(names))
writer.write(' ')
writer.write(' '.join(nums))
#writer.write(' '.join(names+nums)) is nicer but cause list to be concat

I agree with Justin than using zip is a good idea. The problems is how to put the data into two different lists. Here is a proposal that should work ok.

reader = open('input.txt')
writer = open('output.txt', 'w')
names, nums = [], []
row = reader.read().split(' ')
x = len(row)/2
for (a, b) in [(n, v) for n, v in zip(row[:x], row[x:]) if v!='na']:
    names.append(a)
    nums.append(b)
writer.write(' '.join(names))
writer.write(' ')
writer.write(' '.join(nums))
#writer.write(' '.join(names+nums)) is nicer but cause list to be concat
夕嗳→ 2024-09-19 01:13:29

或者说您有一个从文件中读取的字符串。我们将此字符串称为“s”

words = filter(lambda x: x!="na", s.split())

应该为您提供除“na”编辑之外的所有字符串

:上面的代码显然没有执行您想要的操作。

下面的应该可以工作

d = s.split()
keys = d[:len(d)/2]
vals = d[len(d)/2:]
w = " ".join(map(lambda (k,v): (k + " " + v) if v!="na" else "", zip(keys, vals)))
print " ".join([" ".join(w.split()[::2]), " ".join(w.split()[1::2])])

or say you have a string which you have read from a file. Let's call this string as "s"

words = filter(lambda x: x!="na", s.split())

should give you all the strings except for "na"

edit: the code above obviously doesn't do what you want it to do.

the one below should work though

d = s.split()
keys = d[:len(d)/2]
vals = d[len(d)/2:]
w = " ".join(map(lambda (k,v): (k + " " + v) if v!="na" else "", zip(keys, vals)))
print " ".join([" ".join(w.split()[::2]), " ".join(w.split()[1::2])])
攀登最高峰 2024-09-19 01:13:29
strlist = 'namenexttolast nameonemore namethelast 0 na 2'.split()
vals = ('0', '1', '2', '3', '4', 'na')
key_list = [s for s in strlist if s not in vals]
val_list = [s for s in strlist if s in vals]

#print [(key_list[i],v) for i, v in enumerate(val_list) if v != 'na']
filtered_keys = [key_list[i] for i, v in enumerate(val_list) if v != 'na']
filtered_vals = [v for v in val_list if v != 'na']

print filtered_keys + filtered_vals

如果您想对值进行分组,您可以创建一个元组列表(注释掉行)

strlist = 'namenexttolast nameonemore namethelast 0 na 2'.split()
vals = ('0', '1', '2', '3', '4', 'na')
key_list = [s for s in strlist if s not in vals]
val_list = [s for s in strlist if s in vals]

#print [(key_list[i],v) for i, v in enumerate(val_list) if v != 'na']
filtered_keys = [key_list[i] for i, v in enumerate(val_list) if v != 'na']
filtered_vals = [v for v in val_list if v != 'na']

print filtered_keys + filtered_vals

If you'd rather group the vals, you could create a list of tuples instead (commented out line)

浴红衣 2024-09-19 01:13:29

这是一个仅使用迭代器加上单个缓冲区元素的解决方案,没有调用 len 也没有创​​建其他中间列表。 (在Python 3中,只需使用mapzip,无需从itertools导入imapizip。)

from itertools import izip, imap, ifilter

def iterStartingAt(cond, seq):
    it1,it2 = iter(seq),iter(seq)
    while not cond(it1.next()):
        it2.next()
    for item in it2:
        yield item

dataline = "namenexttolast nameonemore namethelast 0 na 2"
datalinelist = dataline.split()

valueset = set("0 1 2 3 4 na".split())

print " ".join(imap(" ".join, 
                    izip(*ifilter(lambda (n,v): v != 'na', 
                                  izip(iter(datalinelist), 
                                       iterStartingAt(lambda s: s in valueset, 
                                                      datalinelist))))))

印刷:

namenexttolast namethelast 0 2

Here is a solution that uses just iterators plus a single buffer element, with no calls to len and no other intermediate lists created. (In Python 3, just use map and zip, no need to import imap and izip from itertools.)

from itertools import izip, imap, ifilter

def iterStartingAt(cond, seq):
    it1,it2 = iter(seq),iter(seq)
    while not cond(it1.next()):
        it2.next()
    for item in it2:
        yield item

dataline = "namenexttolast nameonemore namethelast 0 na 2"
datalinelist = dataline.split()

valueset = set("0 1 2 3 4 na".split())

print " ".join(imap(" ".join, 
                    izip(*ifilter(lambda (n,v): v != 'na', 
                                  izip(iter(datalinelist), 
                                       iterStartingAt(lambda s: s in valueset, 
                                                      datalinelist))))))

Prints:

namenexttolast namethelast 0 2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文