for循环返回最后一个对象而不是前面的python

时间:2015-10-13 15:31:37

标签: python loops for-loop

def excel(vendor_ids):
    for i in vendor_ids:
        t = Test()
        c = pycurl.Curl()
        c.setopt(c.URL, (str("https://api.box.com/2.0/folders/%s")%(i)))
        c.setopt(pycurl.HTTPHEADER, ['Authorization: Bearer %s'%(access_token)])
        c.setopt(c.WRITEFUNCTION, t.body_callback)
        c.perform()
        c.close()
        contents=(t.contents)
        #print(contents)
        jsondict=(json.JSONDecoder().decode(contents))
        collect=(jsondict['item_collection'])
        ids= (collect['entries'])
        dic=[]
        for k in ids:
            print(k)
            return k 


K=excel(vendor_ids)

当我打印以下打印但当我返回时我只得到最后一个

{u'sequence_id': u'0', u'etag': u'0', u'type': u'folder', u'id': u'4322345554', u'name': u'rejected'}
{u'sequence_id': u'0', u'etag': u'0', u'type': u'folder', u'id': u'4392281882', u'name': u'incoming'}
{u'sequence_id': u'0', u'etag': u'0', u'type': u'folder', u'id': u'4392284514', u'name': u'rejected'}
{u'sequence_id': u'0', u'etag': u'0', u'type': u'folder', u'id': u'4866336745', u'name': u'imports'}
{u'sequence_id': u'0', u'etag': u'0', u'type': u'folder', u'id': u'4912855065', u'name': u'Incoming'}
{u'sequence_id': u'0', u'etag': u'0', u'type': u'folder', u'id': u'4912855189', u'name': u'Rejected'}

1 个答案:

答案 0 :(得分:0)

您可以做的是将数据存储到列表中并在最后返回。像这样:

import javax.swing.JOptionPane;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TextInputDialog;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class UniTest extends Application {
    @Override
    public void start(final Stage stage) throws Exception {
        final String s = new String(new int[]{127137, 178050, 3232, 128512, 241}, 0, 5);
        System.out.println("The string: " + s);
        System.out.println("Characters: " + s.length());
        System.out.println("Code points: " + s.codePoints().count());

        JOptionPane.showMessageDialog(null, s, "JOptionPane", JOptionPane.INFORMATION_MESSAGE);

        final Alert al = new Alert(AlertType.INFORMATION);
        al.setTitle("Alert");
        al.setContentText(s);
        al.showAndWait();

        final TextInputDialog dlg = new TextInputDialog();
        dlg.setTitle("TextInputDialog");
        dlg.setContentText("Try to paste the string in here");
        dlg.showAndWait().ifPresent(x -> System.out.println("Your input: " + x));

        final StackPane root = new StackPane();
        root.getChildren().add(new Label(s));
        stage.setScene(new Scene(root, 400, 300));
        stage.setTitle("Stage");
        stage.show();
    }

    public static void main(final String... args) {
        launch(args);
    }
}

但是您的外部循环仍然只迭代一次,我无法真正理解您的代码和用例,但如果您有lst=[] for k in ids: print(k) lst.append(k) return lst 概念,则可以使用yield代替return匹配您的用例。