使用Scala applicative将List [Object]转换为case类(Using Scala applicative to convert List[Object] to case class)
我正在编写一个使用Datomic作为后端数据库的Scala Play Framework应用程序。
当我查询Datomic时,它返回“rows”作为
java.lang.Object
的List
s的java.util.List
。 例如:[ [ "Joe", "1970-04-15" ], [ "Mary", "1975-06-01" ] ]
我想以最可靠的Scala惯用方式将这些转换为案例类。
目前我的代码如下所示:
import org.joda.time._ case class Person(name: String, dateOfBirth: LocalDate) // assuming the query returns 1 row, get the row List val row = result.iterator.next // e.g.: [ "Joe", "1970-04-15" ] User(row.get(0).asInstanceOf[String], LocalDate.parse(row.get(1).asInstanceOf[String]))
这有点丑陋且容易出错。
有没有办法使用applicative functors来实现同样的目的? 应用仿函数是最好的方法吗? 有没有更好的办法?
I am writing a Scala Play Framework application that uses Datomic as a back-end database.
When I query Datomic, it returns "rows" as
java.util.List
s ofList
s ofjava.lang.Object
s. For example:[ [ "Joe", "1970-04-15" ], [ "Mary", "1975-06-01" ] ]
I would like to convert these to case classes in the most Scala-idiomatic way possible.
Currently my code looks like this:
import org.joda.time._ case class Person(name: String, dateOfBirth: LocalDate) // assuming the query returns 1 row, get the row List val row = result.iterator.next // e.g.: [ "Joe", "1970-04-15" ] User(row.get(0).asInstanceOf[String], LocalDate.parse(row.get(1).asInstanceOf[String]))
That's sort of ugly and error-prone.
Is there a way to use applicative functors to achieve the same thing? Are applicative functors the best way to do this? Is there a better way?
原文:https://stackoverflow.com/questions/20841284
最满意答案
看起来你正在使用字典而不是对象。 试试potential_friends.append(Friendship.objects.friends_for_user(friend ['friend']))
It looks like you're using a dictionary not an object. Try potential_friends.append(Friendship.objects.friends_for_user(friend['friend']))
相关问答
更多-
AttributeError:'dict'对象没有属性'_meta'(AttributeError: 'dict' object has no attribute '_meta')[2023-12-18]
序列化expect queryset作为第二个参数 - 你传递的是dicts列表; 文档字符串: def serialize(format, queryset, **options): """ Serialize a queryset (or any iterator that returns database objects) using a certain serializer. """ ... 基本上您的数据几乎是序列化的。 调用简单的json.dumps() ... -
您正在调用该函数并将函数调用的结果传递给队列。 在不调用函数的情况下注册该函数,并且包含要调用时要传递的参数: django_rq.enqueue(create_order_ordrin, foo, bar=baz) 它会被称为create_order_ordrin(foo, bar=baz) 。 You are calling the function and passing in the result of the function call to the queue. Register the fu ...
-
所以我经过一些挖掘后找到了答案,这确实是Python2和Python3之间的区别,这是一个非常重要的。 事实证明,代码中的类型Resource实际上是一个命名元组。 在Python2中, .__dict__被添加为._asdict()方便属性包装器,但这不是在Python3中完成的: https://docs.python.org/2/library/collections.html#collections.somenamedtuple._asdict (在此处查找__dict__ ) https://do ...
-
发生错误是因为请求不期望files dict中的项目的字典。 根据文档 ,使用一个简单的元组应该工作: files = {'file': (f["filename"], f["body"])} The error is occurring because requests doesn't expect a dictionary for the items in the files dict. According to the documentation, using a simple tuple shou ...
-
AttributeError:'dict'对象没有属性'read'(AttributeError: 'dict' object has no attribute 'read')[2023-07-02]
results=api.search(q="microsoft",count=100) print type(results) print json.load(results) 这里的results已经是一个dict 。 没有必要将其反序列化为JSON。 请参阅: tweepy.api.API.search() ,其内容如下: API.search(q[, lang][, locale][, rpp][, page][, since_id][, geocode][, show_user]) Return ... -
您不能在占位符中调用方法。 您可以访问属性和属性甚至索引值 - 但您无法调用方法: class Fun(object): def __init__(self, vals): self.vals = vals @property def keys_prop(self): return list(self.vals.keys()) def keys_meth(self): return list(self.vals.keys() ...
-
对于用户定义的类(在常规Python代码中使用class关键字定义),类将始终有__slots__类, __dict__实例或两者(如果其中一个定义为'__dict__' ,或者其中一个用户继承链中定义的类定义__slots__ ,另一个不包含,隐式创建__dict__ )。 这是用户定义类的四种可能性中的三种。 编辑:更正:从技术上讲,用户定义的类可能没有 ; 该类将使用__slots__进行定义,但在定义时间之后将其删除(在类定义完成后,设置该类型的机器不需要__slots__继续存在)。 没有一个理智 ...
-
看起来你正在使用字典而不是对象。 试试potential_friends.append(Friendship.objects.friends_for_user(friend ['friend'])) It looks like you're using a dictionary not an object. Try potential_friends.append(Friendship.objects.friends_for_user(friend['friend']))
-
此错误消息有你的答案。 https://docs.python.org/2/tutorial/datastructures.html#dictionaries data['users'] = [dat] 如果要附加到现有列表。 templist = data['users'] templist.extend(dat) data['users'] = templist This error message has your answer. https://docs.python.org/2/tutori ...
-
如果不指定第二个参数,则默认值为None。 (见dict.fromkeys ) >>> n = 3 >>> count_dict = dict.fromkeys(range(0,n+1)) >>> count_dict {0: None, 1: None, 2: None, 3: None} 除此之外, dict.fromkeys创建的值由所有条目共享。 >>> count_dict = dict.fromkeys(range(0,n+1), []) >>> count_dict {0: [], 1: [ ...