我的输入有一个dictonary有以下特点:
例如:
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)
我觉得这可以用更干净的方式完成,有任何改进建议吗?
我正在尝试对实现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) 关于迭代器的一种奇怪的问题.在调查一个不同的问题时,我发现了以下内容.这是一个可行的迭代:
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) 我想实现一个类似数组的类:
我看到这样的:
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) 我有一个字典的以下包装器:
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迭代.任何意见,将不胜感激.
我们考虑一个文件:
$ 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) 让我们假设一个具有已定义迭代器的对象的两个类似实现:一个使用生成器的迭代器,另一个使用迭代.这两个都可以使用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) 也许似乎是dum但我知道如果我想声明一个列表我可以这样做:
list1 = list("Hello")
Run Code Online (Sandbox Code Playgroud)
但为什么我需要2组括号来声明数字:
list2 = list((2,3,4,5))
Run Code Online (Sandbox Code Playgroud) 使用基于路径的资源系统,应用程序需要根据路径查找管理给定资源的第一个工作资源.我需要一种简洁,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或类似的内置函数,但这些不是文件系统资源.输出可以是任何可迭代的(列表,集合,生成器等).
我正在尝试运行这段代码,并且收到一条错误消息'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) iterable ×10
python ×7
dictionary ×2
generator ×2
javascript ×2
list ×2
arguments ×1
arrays ×1
built-in ×1
class ×1
ecmascript-6 ×1
int ×1
iterator ×1
java ×1
junit ×1
linked-list ×1
object ×1
python-2.7 ×1
sorting ×1
typescript ×1