标签: iterable

Python字典来排序元组,这可以做得更好吗?

我的输入有一个dictonary有以下特点:

  • 每个值都可以是整数,字符串或可迭代(除了字符串).
  • 如果元素是可迭代的,则该iterable中的每个元素将只是一个字符串或整数.

例如:

mydict = {
    'one': 1,
    'two': '23',
    'three': 3,
    'four': [
        7,
        '6',
        5,
        8
    ],
    'nine': 9
}
Run Code Online (Sandbox Code Playgroud)

我需要将输入转换为元组列表,其中每个元组是键/值对.对于可迭代元素,每个元素都有一个键/值对,按值排序.例如,上面的输出应该是:

('four', 5)
('four', 7)
('four', 8)
('four', '6')
('nine', 9)
('one', 1)
('three', 3)
('two', '2')
Run Code Online (Sandbox Code Playgroud)

我目前使用以下生成器实现了这个:

def dict_to_sorted_tuples(unsorted_dict):
    for key in sorted(unsorted_dict):
        if isinstance(unsorted_dict[key], basestring):
            yield key, unsorted_dict[key]
            continue
        try:
            for v in sorted(unsorted_dict[key]):
                yield key, v
        except:
            yield key, unsorted_dict[key]

print list(dict_to_sorted_tuples(mydict))
Run Code Online (Sandbox Code Playgroud)

我觉得这可以用更干净的方式完成,有任何改进建议吗?

python sorting dictionary iterable generator

1
推荐指数
1
解决办法
150
查看次数

Junit实现了Iterable

我正在尝试对实现Iterable的类进行测试.当我去测试任何方法时,在itorator类中,如hasNext(),next().所以当我调用list.itorator().Next(); 没有任何反应,节点是列表中的当前节点而不是下一个节点.但是当我做ListIterator时itrList = new ListIterator(list); 里面的代码有效.我正在调用public Iterator iterator(){return new ListIterator(this); 那我在做什么不正确/抓?谢谢你的帮助.

public void test6() {
    List<String> list = new List<String>();

    list.addAfterCurrent("1");
    list.addAfterCurrent("2");
    list.addAfterCurrent("3");
    ListIterator itrList = new ListIterator(list);


    TextIO.putln(list.iterator().next()); // output is 1
    TextIO.putln(list.iterator().next()); // output is 1 
    TextIO.putln(itrList.next());         // output is 1
    TextIO.putln(itrList.next());         // now output is 2           
    assertEquals("1", list.getCurrent());
    assertEquals(3, list.size());

}
Run Code Online (Sandbox Code Playgroud)

java junit iterable linked-list

1
推荐指数
1
解决办法
1264
查看次数

在构造函数中分配__iter__的类未被识别为迭代器

关于迭代器的一种奇怪的问题.在调查一个不同的问题时,我发现了以下内容.这是一个可行的迭代:

class CacheGen(object):
    def __init__(self, iterable):
        if isinstance(iterable, (list, tuple, dict)):
            self._myiter = iterable
        else:
            self._myiter = list(iterable)
    def __iter__(self):
        return self._myiter.__iter__()
    def __contains__(self, key):
        return self._myiter.__contains__(key)
    def __getitem__(self, key):
        return self._myiter.__getitem__(key)
Run Code Online (Sandbox Code Playgroud)

这是一个类似的迭代,但不是:

class CacheGen2(object):
    def __init__(self, iterable):
        if isinstance(iterable, (list, tuple, dict)):
            self._myiter = iterable
        else:
            self._myiter = list(iterable)
        self.__iter__ = self._myiter.__iter__
        self.__contains__ = self._myiter.__contains__
        self.__getitem__ = self._myiter.__getitem__
Run Code Online (Sandbox Code Playgroud)

请注意,它们实际上是在做同样的事情,但是一个委托,另一个只是将我的类构造函数分配给列表.有什么想法吗?注意它在类中有一个iter函数,我可以直接调用它并获得一个有效的迭代器,但是'normal'函数不起作用.

xr = xrange(100)
cg = CacheGen(xr)
list(cg)
[0,1,2,3...

cg2 = CacheGen2(xr)
list(cg2)
TypeError                                 Traceback (most recent call last) …
Run Code Online (Sandbox Code Playgroud)

python iterable list

1
推荐指数
1
解决办法
492
查看次数

如何使用Typescript的自定义方法实现类似数组的类?

我想实现一个类似数组的类:

  1. 接受数组作为构造函数的参数
  2. 应该是可迭代的,并具有所有内置数组的方法
  3. 有一些自定义方法
  4. 应该可以扩展其他类

我看到这样的:

class BaseModel {
  arr: Array;

  constructor(arr: Array<any>) { // <= req. #1
    this.arr = arr;
  }

  serialize(arr) { // <= req. #3
    this.arr = arr;
  }
}

class ListModel extends BaseModel { // <= req. #4
  constructor(arr: Array<any>) { // <= req. #1
    super(arr);
  }

  sayHello() { // <= req. #3
    console.log('hello');
  }
}

let list = new ListModel([1,2,3]);
list.sayHello();
// expected output:
// 'hello'
list.push(4); // <= req. #2

for (let a of …
Run Code Online (Sandbox Code Playgroud)

javascript arrays iterable class typescript

1
推荐指数
1
解决办法
827
查看次数

如何实现字典对象的"下一步"可迭代?

我有一个字典的以下包装器:

class MyDict:
    def __init__(self):
        self.container = {}

    def __setitem__(self, key, value):
        self.container[key] = value

    def __getitem__(self, key):
        return self.container[key]

    def __iter__(self):
        return self

    def next(self):
        pass

dic = MyDict()
dic['a'] = 1
dic['b'] = 2

for key in dic:
    print key
Run Code Online (Sandbox Code Playgroud)

我的问题是我不知道如何实现next方法来进行MyDict迭代.任何意见,将不胜感激.

python dictionary iterator iterable python-2.7

1
推荐指数
2
解决办法
2443
查看次数

Python中iter函数的第二个参数是什么?

我们考虑一个文件:

$ echo -e """This is a foo bar sentence .\nAnd this is the first txtfile in the corpus .""" > test.txt
$ cat test.txt 
This is a foo bar sentence .
And this is the first txtfile in the corpus .
Run Code Online (Sandbox Code Playgroud)

当我想逐个阅读文件时,我可以做/sf/answers/1755011331/:

>>> fin = open('test.txt')
>>> while fin.read(1):
...     fin.seek(-1,1)
...     print fin.read(1),
... 
T h i s   i s   a   f o o   b a r   s e n t e n c e   . …
Run Code Online (Sandbox Code Playgroud)

python arguments iterable built-in

1
推荐指数
1
解决办法
1027
查看次数

Iterables:带有迭代器的对象或生成器

让我们假设一个具有已定义迭代器的对象的两个类似实现:一个使用生成器的迭代,另一个使用迭代.这两个都可以使用Array.from,并且它们都可以迭代.这两种方法有哪些区别,哪一种更受欢迎,为什么?是否需要较小的方法?

class Foo {
  constructor( ...args ) {
    this.f = args;
  }
  [Symbol.iterator]() {
    let c = 0;

    const i = {

      next: () => {
        if ( c < this.f.length ) {
          return {value:this.f[c++], done: false};
        }
        else {
          return {value:undefined,done:true};
        }
      }

    };
    return i;
  }

};

class Bar {
  constructor( ...args ) {
    this.f = args;
  }
  *[Symbol.iterator]() {
    let c = 0;

    if ( c < this.f.length ) …
Run Code Online (Sandbox Code Playgroud)

javascript iterable generator ecmascript-6

1
推荐指数
1
解决办法
52
查看次数

为什么我需要2对括号来声明数字列表

也许似乎是dum但我知道如果我想声明一个列表我可以这样做:

list1 = list("Hello")
Run Code Online (Sandbox Code Playgroud)

但为什么我需要2组括号来声明数字:

list2 = list((2,3,4,5))
Run Code Online (Sandbox Code Playgroud)

python iterable list

1
推荐指数
1
解决办法
91
查看次数

Python:获得路径中所有父项的可迭代的优雅方式

使用基于路径的资源系统,应用程序需要根据路径查找管理给定资源的第一个工作资源.我需要一种简洁,pythonic的方式来生成以下内容:

输入:

/house/dogs/ralph/bone
Run Code Online (Sandbox Code Playgroud)

输出:

/house/dogs/ralph/bone
/house/dogs/ralph
/house/dogs
/house
Run Code Online (Sandbox Code Playgroud)

注意:可以使用os.path或类似的内置函数,但这些不是文件系统资源.输出可以是任何可迭代的(列表,集合,生成器等).

python iterable

1
推荐指数
1
解决办法
104
查看次数

如何解决:“ int”对象不可迭代

我正在尝试运行这段代码,并且收到一条错误消息'int' object is not iterable for line 10。不知道我哪里出错了。

def inputVal(prompt,lower,upper):
    print(prompt)
    retVal = int(input())
    while retVal<lower or retVal>upper:
        print('Incorrect Value')
        retVal = int(input())
    return retVal

numComp = inputVal("Please enter number of competitors", 5, 20)

for comp in numComp:
    total=0
    for i in range(5):
        judgescore = inputVal('Please input judges score', 0, 10)
        total = total + judgescore
    print("Total judge score for competitor ", comp+1, "is: ", total)
    print("Average judge score for competitor ", comp+1, "is: ", total/5)
Run Code Online (Sandbox Code Playgroud)

python int iterable object

1
推荐指数
1
解决办法
41
查看次数