如何迭代不同列表的产品?

时间:2016-10-01 09:10:43

标签: python list python-3.x for-loop itertools

我有以下问题:

我有一个列表l1,我希望使用函数itertools.product迭代产品,我还希望以相同的方式包含第二个列表l2

例如:

l1 = [1, 2, 3, 4]
l2 = ['a', 'b', 'c', 'd']
for i in list(itertools.product(l1, repeat = 2)):
    print(i)

输出结果为:

(1, 1)
(1, 2)
...

我认为这很清楚。但是,如何设置包含第二个列表并获得如下输出:

(1, a),(1, a)
(1, a),(2, b)
(1, a),(3, c)
(1, a),(4, d)

(2, b),(1, a)
(2, b),(2, b)
(2, b),(3, c)
(2, b),(4, d)

(3, c),(1, a)
(3, c),(2, b)
(3, c),(3, c)
(3, c),(4, d)

(4, d),(1, a)
(4, d),(2, b)
(4, d),(3, c)
(4, d),(4, d)

我知道一个合适的解决方案是组合for循环。但这不适合我,因为我想增加repeat - 反击。

1 个答案:

答案 0 :(得分:3)

{ "responseHeader":{ "status":0, "QTime":2, "params":{ "q":"test_field:*test*", "indent":"true", "wt":"json"}}, "response":{"numFound":1,"start":0,"docs":[ { "id":"change.me", "test_field":["test"], "_version_":1546932094148542464}] }} 提供private void registerUser(){ String emailId = email.getText().toString().trim().toLowerCase(); String password = pass.getText().toString().trim(); firebaseAuth.createUserWithEmailAndPassword(emailId,password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { progressDialog.dismiss(); if(task.isSuccessful()){ Toast.makeText(MainActivity.this,"Registration Successful",Toast.LENGTH_SHORT).show(); //show chatroom finish(); startActivity(new Intent(getApplicationContext(),ProfileActivity.class)); } else{ Toast.makeText(MainActivity.this,"Registration Failed. Please try again",Toast.LENGTH_SHORT).show(); } } }); } 个列表:

zip

不需要在product中包装,for循环负责为您调用迭代器上的for i in product(zip(l1,l2), repeat = 2): print(i)

如果您想要每4个组合使用一个新行,请使用list(从next开始)并在enumerate1时添加\n

c % 4

输出:

0