我搜索了很多答案,但我只能找到多次添加一个项目的答案。或者只是将两个列表相乘。
#ratio of bar
ratio_variant1 = 0.1
ratio_variant2 = 0.3
ratio_variant3 = 0.4
ratio_variant4 = 0.2
ratio = []
ratio.extend([ratio_variant1, ratio_variant2, ratio_variant3, ratio_variant4])
#ratio to integer
ratiointeger = [x*100 for x in ratio]
#size of bar
size_variant1 = 2
size_variant2 = 3
size_variant3 = 4
size_variant4 = 6
size = []
size.extend([size_variant1, size_variant2, size_variant3, size_variant4])
bucket = size * ratiointeger
我担心我创建比率和大小列表的方式并不是真正的pythonic,但主要问题是我无法创建列表/存储桶:
10 items of 2
30 items of 3
40 items of 4
20 items of 6
答案 0 :(得分:0)
试试这个:
bucket = [[s] * int(r) for (s, r) in zip(size, ratiointeger)]
答案 1 :(得分:0)
在我看来,你需要:
>>> [[s]*r for s, r in zip(size, ratiointeger)]
[[2, 2, 2, 2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]]
这将构建一个列表列表,其中包含您想要的重复:
#ifndef TESTCLASS_H
#define TESTCLASS_H
#include <QObject>
#include <QMap>
#include <QColor>
class TestClass : public QObject
{
Q_OBJECT
public:
explicit TestClass(QObject *parent = 0);
// mutators
void setColor(const QString& aName, const QColor& aColor);
QColor getColor(const QString &aName) const;
private:
QMap<QString, QColor> mColors;
};
#endif // TESTCLASS_H
然后使用the method from this post展平它们。