1

例えば

組織リスト:

aa b2 c d

マッピング :

aa 1
b2 2
d 3
c 4

gen_list:

1 2 4 3

これを実装するPythonの方法は何ですか? org_list とマッピングがファイルorg_list.txtmapping.txtにあり、gen_list がに書き込まれるとします。gen_list.txt

ところで、これを実装するのに非常に簡単な言語はどれだと思いますか?

4

5 に答える 5

5

リスト内包表記でリストをループするだけです:

gen_list = [mapping[i] for i in org_list]

デモ:

>>> org_list = ['aa', 'b2', 'c', 'd']
>>> mapping = {'aa': 1, 'b2': 2, 'd': 3, 'c': 4}
>>> [mapping[i] for i in org_list]
[1, 2, 4, 3]

このデータがファイルにある場合は、まずメモリ内にマッピングを構築します。

with open('mapping.txt') as mapfile:
    mapping = {}
    for line in mapfile:
        if line.strip():
            key, value = line.split(None, 1)
            mapping[key] = value

次に、入力ファイルから出力ファイルを作成します。

with open('org_list.txt') as inputfile, open('gen_list.txt', 'w') as outputfile:
    for line in inputfile:
        try:
            outputfile.write(mapping[line.strip()] + '\n')
        except KeyError:
            pass  # entry not in the mapping
于 2013-04-21T21:39:44.920 に答える
4

これがあなたのケースの解決策です。

with open('org_list.txt', 'rt') as inp:
    lines = inp.read().split()
    org_list = map(int, lines)

with open('mapping.txt', 'rt') as inp:
    lines = inp.readlines()
    mapping = dict(line.split() for line in lines)

gen_list = (mapping[i] for i in org_list) # Or you may use `gen_list = map(mapping.get, org_list)` as suggested in another answers

with open('gen_list.txt', 'wt') as out:
    out.write(' '.join(gen_list))

Python はこの状況を十分にうまく処理していると思います。

于 2013-04-21T21:39:46.103 に答える
3

別の方法:

In [1]: start = [1,2,3]
In [2]: mapping = {1: "one", 2: "two", 3: "three"}
In [3]: map(mapping.get, start)
Out[3]: ['one', 'two', 'three']
于 2013-04-21T21:45:32.907 に答える
1

map()またはリスト内包表記を使用してみてください。

>>> org_list = ['aa', 'b2', 'c', 'd']
>>> mapping = {'aa': 1, 'b2': 2, 'd': 3, 'c': 4}

>>> map(mapping.__getitem__, org_list)
[1, 2, 4, 3]

>>> [mapping[x] for x in org_list]
[1, 2, 4, 3]
于 2013-04-21T21:50:56.663 に答える
0
mapping = dict(zip(org_list, range(1, 5)))       # change range(1, 5) to whatever
gen_list = [mapping[elem] for elem in org_list]  # you want it to be
于 2013-04-21T22:03:25.470 に答える