使用python循环出错

时间:2016-07-04 14:47:16

标签: python loops

我有列表lst = [1, 2, 3, 4, 5, 6, 3, 5, 3]和每次迭代,其中elem == 3我想在此之前打印字符串,而elem不再是3。 我想得到

2 3:
0 1
1 2
6 3:
3 4
4 5
5 6
8 3:
7 5

但我不知道,如何转到上一个字符串

for i, el in enumerate(lst):
    if lst[i] == 3:
        print i, el
        i -= 1

但它是elem-1

2 个答案:

答案 0 :(得分:1)

这样的东西?

module.exports = React.createClass({

onPoliciesChange: function (policiesStore) {
    this.setState(policiesStore);
},

getInitialState: function () {
    return {
        policies: []
    };
},

componentDidMount: function () {
    this.unsubscribeAlertsStore = AlertsStore.listen(this.onPoliciesChange);
},

componentWillUnmount: function () {
    this.unsubscribeAlertsStore();
},


cols: [
    { key: 'name', label: 'Name'},
    { key: 'severity', label: 'Severity' },
    { key: 'width', label: 'Width' },
    { key: 'pulsate', label: 'Pulsate' }        
],

generateHeaders: function () {
    var cols = this.cols;  // [{key, label}]

    // generate our header (th) cell components
    return cols.map(function (colData) {
        return <th key={colData.key}> {colData.label} </th>;
    });
},

generateRows: function () {
    var slf = this;
    var cols = this.cols,  // [{key, label}]
        data = this.data;
    //per each item 
    return this.state.policies.map(function (item) {
        // handle the column data within each row
        var cells = cols.map(function (colData) {
            return <td> {item[colData.key]} </td>;          
        });
        return <tr key={item.id}> {cells} </tr>;
    });
},

render: function () {

    var headerComponents = this.generateHeaders(),
        rowComponents = this.generateRows();
    return (
        <table className="table table-condensed table-striped">
            <thead> {headerComponents} </thead>
                <tbody> {rowComponents} </tbody>
            </table>
        );
    }
});

答案 1 :(得分:1)

您可以尝试使用切片实现,如下所示:

lst = [1, 2, 3, 4, 5, 6, 3, 5, 3]

start_pos = 0
for idx, val in enumerate(lst):
    if val == 3:
        print idx,val,":"
        for p_idx, p_val in enumerate(lst[start_pos:idx]):
            print p_idx+start_pos,p_val
        start_pos = idx+1