移调阵列 [英] Transposing arrays
问题描述
我用下面的code在CSV文件中读取:
I am using the following code to read in a CSV file:
String next[] = {};
List<String[]> dataArray = new ArrayList<String[]>();
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("inputFile.csv")));
for(;;) {
next = reader.readNext();
if(next != null) {
dataArray.add(next);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
这变成一个CSV文件导入阵列dataArray的。我的申请为字典类型的应用程序 - 输入数据的第一列是词语的列表,而第二列是这些词语的定义。这里是在装载的阵列的示例:
This turns a CSV file into the array 'dataArray'. My application is for a dictionary type app - the input data's first column is a list of words, and the second column is the definitions of those words. Here is an example of the array loaded in:
Term 1, Definition 1
Term 2, Definition 2
Term 3, Definition 3
为了访问字符串之一在数组中,我用下面的code:
In order to access one of the strings in the array, I use the following code:
dataArray.get(rowNumber)[columnNumber]
然而,我需要能够生成所有术语的列表,以便它们可以被显示为字典应用。据我了解,自己访问的列是一个更加漫长的过程不是访问行(我来自一个MATLAB的背景下,这哪里会是简单)。
However, I need to be able to generate a list of all the terms, so that they can be displayed for the dictionary application. As I understand it, accessing the columns by themselves is a much more lengthy process than accessing the rows (I come from a MATLAB background, where this would be simple).
看来,为了要我输入数据的任何行随时访问,我会过得更好移调数据,并以这种方式阅读它;即:
It seems that in order to have ready access to any row of my input data, I would be better off transposing the data and reading it in that way; i.e.:
Term 1, Term 2, Term3
Definition 1, Definition 2, Definition 3
当然,我可以只提供在第一位置调换一个CSV文件 - 但Excel或OO计算器不允许超过256行,我的字典包含约2000项
Of course, I could just provide a CSV file that is transposed in the first place - but Excel or OO Calc don't allow more than 256 rows, and my dictionary contains around 2000 terms.
以下任何解决方案将受到欢迎:
Any of the following solutions would be welcomed:
- 一旦被读取到转数组的方式
- 一个改变到code上面贴,使得它在数据中的换位的方式读
- 一个简单的方法来读取阵列的整列作为一个整体
推荐答案
您可能会得到更好的利用地图数据结构(如的 HashMap的):
You would probably be better served by using a Map data structure (e.g. HashMap):
String next[] = {};
HashMap<String, String> dataMap = new HashMap<String, String>();
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("inputFile.csv")));
for(;;) {
next = reader.readNext();
if(next != null) {
dataMap.put(next[0], next[1]);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
然后你可以通过
dataMap.keySet();
和
dataMap.values();
请注意一个假设的位置:您输入数据的第一列是所有唯一值(也就是,有没有在期限列中重复的值)
Note one assumption here: that the first column of your input data is all unique values (that is, there are not repeated values in the "Term" column).
要能够访问密钥(计算)为一个数组,你可以简单地做如下:
To be able to access the keys (terms) as an array, you can simply do as follows:
String[] terms = new String[dataMap.keySet().size()];
terms = dataMap.keySet().toArray(terms);
这篇关于移调阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!