我有以下代码:
dataList
我想要的输出格式是:
dataList
但是,鉴于上述代码,其结果为:
>>> from collections import Counter
>>> from pprint import pprint
>>> dataList = [{'Key': 'US', 'Val': 'NewYork'},
... {'Key': 'Aus', 'Val': 'Sydney'},
... {'Key': 'US', 'Val': 'Washington'},
... {'Key': 'Ind', 'Val': 'Delhi'},
... {'Key': 'Fra', 'Val': 'Paris'},
... {'Key': 'Ind', 'Val': 'Chennai'}]
>>> key_counts = Counter(d['Key'] for d in dataList)
>>> key_counts
Counter({'US': 2, 'Ind': 2, 'Aus': 1, 'Fra': 1})
>>> uniqueValues = []
>>> duplicateValues = []
>>> for d in dataList:
... if key_counts[d['Key']] == 1:
... uniqueValues.append(d)
... else:
... duplicateValues.append(d)
...
>>> pprint(uniqueValues)
[{'Key': 'Aus', 'Val': 'Sydney'}, {'Key': 'Fra', 'Val': 'Paris'}]
>>> pprint(duplicateValues)
[{'Key': 'US', 'Val': 'NewYork'},
{'Key': 'US', 'Val': 'Washington'},
{'Key': 'Ind', 'Val': 'Delhi'},
{'Key': 'Ind', 'Val': 'Chennai'}]
如何摆脱定界符StringJoiner stringJoiner = new StringJoiner(",");
List<Person> persons = Arrays.asList(new Person("Juan", "Dela Cruz"), new Person("Maria", "Magdalena"), new Person("Mario", "Santos"));
persons.forEach(person -> {
stringJoiner.add(person.getFirstName()).add(person.getLastName() + System.lineSeparator());
});
作为每一行的第一个字符?
谢谢。
答案 0 :(得分:5)
另一种解决方案,使用流和联接收集器:
String result = persons.stream()
.map(person -> person.getFirstName() + "," + person.getLastName())
.collect(Collectors.joining(System.lineSeparator()));
答案 1 :(得分:3)
您的记录定界符是换行符,因此您可能要在for-each中使用逗号(即,将换行符和逗号替换为换行符):
StringJoiner stringJoiner = new StringJoiner(System.lineSeparator());
...
persons.forEach(person -> stringJoiner.add(person.getFirstName() +
", " + person.getLastName()));
答案 2 :(得分:1)
为什么不只是覆盖Person类的toString方法,或者为什么在Person类中具有返回联接String的实用程序方法呢?然后您的代码将简单地完成迭代和合并的工作:
public static String getName(){
return String.format("%s,%s", this.firstName, this.lastName);
}
然后使用以下或任何适当的机制进行迭代和减少:
persons.stream()
.map(Person::getName)
.collect(Collectors.joining(System.lineSeparator()));