从列表元素生成新的列表对

时间:2019-03-16 13:14:20

标签: python-3.x list

和键列表。我想创建一个新的对列表,每次增加新对列表中的元素数量。我为此编写了一个简短的python代码,但是它没有达到我的预期,我找不到我在哪里做错了。

/*I am working with turbo c++ compiler so namespace std is not used by me.Also i am familiar with turbo.*/

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<fstream.h> //required while dealing with files
void main ()
{
clrscr();
ofstream fout; //object created **fout**
fout.open("your desired file name + extension");
fout<<"contents to be written inside the file"<<endl;
fout.close();
getch();
} 

预期结果:

    keys = ['83eb48aa3c770a55eb194b3e8c8207e3', 'cc657723152be15805bb53894486653c', 'cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cbbcfce733b1ae42c044131aab3e9439']
    k = 'cbbcfce733b1ae42c044131aab3e9439'
    freq = []
    pair = [k]

    for key in keys:
        pair.append(key)
        freq.append(pair)

    print(freq)

但是我得到了以下结果:

[['cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3'],
['cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cc657723152be15805bb53894486653c'],
['cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cc657723152be15805bb53894486653c', 'cbbcfce733b1ae42c044131aab3e9439'],
['cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cc657723152be15805bb53894486653c', 'cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3'],
['cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cc657723152be15805bb53894486653c', 'cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cbbcfce733b1ae42c044131aab3e9439']]

我花了一个多小时,但找不到我做错了什么地方。

1 个答案:

答案 0 :(得分:0)

需要使用.copy()函数来创建对列表元素的副本,当附加到另一个列表时,似乎python链接到了列表变量。要复制当前列表,需要使用.copy(),例如:

[['cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cc657723152be15805bb53894486653c', 'cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cbbcfce733b1ae42c044131aab3e9439'], ['cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cc657723152be15805bb53894486653c', 'cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cbbcfce733b1ae42c044131aab3e9439'], ['cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cc657723152be15805bb53894486653c', 'cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cbbcfce733b1ae42c044131aab3e9439'], ['cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cc657723152be15805bb53894486653c', 'cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cbbcfce733b1ae42c044131aab3e9439'], ['cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cc657723152be15805bb53894486653c', 'cbbcfce733b1ae42c044131aab3e9439', '83eb48aa3c770a55eb194b3e8c8207e3', 'cbbcfce733b1ae42c044131aab3e9439']]