将列表重复到最大元素长度的最有效方法是什么?
采取这个:
list = ['one', 'two', 'three']
max_length = 7
产生这个:
final_list = ['one', 'two', 'three', 'one', 'two', 'three', 'one']
答案 0 :(得分:7)
我可能会使用iterools.cycle
和itertools.islice
:
>>> from itertools import cycle, islice
>>> lst = [1, 2, 3]
>>> list(islice(cycle(lst), 7))
[1, 2, 3, 1, 2, 3, 1]
答案 1 :(得分:2)
适当地加倍?
var App = React.createClass({
render() {
return (
<div>
<ElementOne id="abc12345"/>
<ElementTwo/>
</div>
);
}
});
var ElementOne = React.createClass({
getInitialState() {
return ({isShowing: true});
},
render() {
if (this.state.isShowing) {
return (
<div id="abc12345">
<h1>Hello World!</h1>
</div>
);
} else {
return <div/>;
}
}
});
var ElementTwo = React.createClass({
render() {
return <a href="#" onClick={this.toggle.bind(null,this)}>Click here to Show/Hide!</a>;
},
toggle() {
var myElementOne = document.getElementById("abc12345");
myElementOne.setState({isShowing: false});
}
});
ReactDOM.render(<App/>,document.getElementById('content'));
基准矿和mgilson的解决方案,我看起来效率更高,例如对于下面的测试矿需要大约0.7秒,而mgilson需要大约2.8秒。
>>> lst = ['one', 'two', 'three']
>>> max_length = 7
>>>
>>> q, r = divmod(max_length, len(lst))
>>> q * lst + lst[:r]
['one', 'two', 'three', 'one', 'two', 'three', 'one']