迭代器product

from itertools import product
pinyin_list = [[u'shei shi', u'shui shi'], [u'kai fa'], [u'jiao cheng']]
keys = []
for i in range(len(pinyin_list)):
    tmp_keys = [item for item in pinyin_list[i]]
    # print tmp_keys
    if i >= 1:
        keys = [' '.join(item) for item in product(keys, tmp_keys)]
        # print keys
    else:
        keys = tmp_keys
print keys

product(iter1, iter2, ... iterN, [repeat=1]):

创建一个迭代器,生成表示item1,item2等中的项目的笛卡尔积的元组,repeat是一个关键字参数,指定重复生成序列的次数。

1  def product(*args, **kwds):
2      # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
3      # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
4      pools = map(tuple, args) * kwds.get('repeat', 1)
5      result = [[]]
6      for pool in pools:
7          result = [x+[y] for x in result for y in pool]
8      for prod in result:
9          yield tuple(prod)
神奇的迭代器。。。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
模式是一种行为型设计模式,它提供一种访问聚合对象中各个元素的方法,而不需要暴露聚合对象的内部结构。在实验销售管理系统中,我们可以使用模式来访问产品列表中的各个产品,而不需要暴露产品列表的内部实现。 首先,我们需要定义一个产品类,它包含产品的名称、价格等基本信息。然后,我们定义一个产品列表类,它包含一个产品数组和相关的方法,如添加产品、获取产品数量等。在产品列表类中,我们实现一个接口,包含 hasNext() 和 next() 方法,用于遍历产品列表中的各个产品。 下面是一个简单的示例代码: ```java // 产品类 public class Product { private String name; private double price; public Product(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public double getPrice() { return price; } } // 产品列表类 public class ProductList implements Iterable<Product> { private List<Product> products = new ArrayList<>(); public void addProduct(Product product) { products.add(product); } public int getProductCount() { return products.size(); } public Product getProduct(int index) { return products.get(index); } // 实现接口 public Iterator<Product> iterator() { return new ProductIterator(); } // 类 private class ProductIterator implements Iterator<Product> { private int index = 0; public boolean hasNext() { return index < products.size(); } public Product next() { return products.get(index++); } } } // 测试代码 public class Test { public static void main(String[] args) { ProductList productList = new ProductList(); productList.addProduct(new Product("手机", 1999.0)); productList.addProduct(new Product("电脑", 4999.0)); productList.addProduct(new Product("平板", 2999.0)); // 使用遍历产品列表 for (Product product : productList) { System.out.println(product.getName() + ": " + product.getPrice()); } } } ``` 在上面的示例代码中,我们定义了一个 Product 类表示产品,一个 ProductList 类表示产品列表。ProductList 类实现了 Iterable 接口,包含一个ProductIterator,用于遍历产品列表中的各个产品。在测试代码中,我们使用遍历产品列表,并输出产品的名称和价格。 通过使用模式,我们可以在不暴露产品列表内部实现的情况下,访问产品列表中的各个产品。这样可以提高代码的灵活性和可维护性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值