如何将数据从每 10 行移动到单行



2 行的数据应移动到第 1 行的数据旁边。应该每 10 行执行此操作。就好像数据集是 20x10 的矩阵一样,它应该变成 2x100。

输入:
1 - 阿 乙 中 德 英 法 G
2 - H I J K L M N
.
.
.
10 - O P Q R S T U

输出:
1 - A B C D E F G H I J K L M N . .O P Q R S T U

假设你想从文件中读取,并且你可能对Python相对较新,这里有一些示例代码供你查看。 我试图添加足够的评论和安全检查,让你了解它是如何工作的,以及你可以如何扩展它。

请注意,您仍然需要对这个python版本中的结果做一些事情,如果您可以使用它,我会强烈考虑@Marcs优雅的答案。

这里需要考虑很多假设。 你有多确定每行都有相同数量的东西? 我添加了一些逻辑来检查这一点,我发现像这样谦虚偏执是有帮助的。

假设您要从文件中读取,这里有一个示例程序供您考虑:

输出

line_cnt=1 #things=3, line="a b c"
line_cnt=2 #things=3, line="d e f"
line_cnt=3 #things=3, line="g h i"
gathered 3 into=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
line_cnt=4 #things=3, line="j k l"
line_cnt=5 #things=3, line="m n o"
line_cnt=6 #things=3, line="p q r"
gathered 3 into=['j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r']
line_cnt=7 #things=3, line="s t v"
line_cnt=8 #things=3, line="u w x"
line_cnt=9 #things=3, line="y z 0"
gathered 3 into=['s', 't', 'v', 'u', 'w', 'x', 'y', 'z', '0']
line_cnt=10 #things=3, line="1 2 3"
line_cnt=11 #things=3, line="4 5 6"
line_cnt=12 #things=3, line="7 8 9"
gathered 3 into=['1', '2', '3', '4', '5', '6', '7', '8', '9']
now have 4 rows
rows=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
['j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r']
['s', 't', 'v', 'u', 'w', 'x', 'y', 'z', '0']
['1', '2', '3', '4', '5', '6', '7', '8', '9']
Process finished with exit code 0

源代码

import io
def join_dataset(f, nrows=10):
    temp_row = [ ]
    consolidated_rows = [ ]
    expected_row_size = None
    line_cnt = 0
    for line in f:
        line_cnt += 1 # want one-based line numbering so not using enumerate
        line = line.strip() # remove trailing newline
        things = line.split() # create list based on whitespace
        row_size = len(things) # check how long this row's list is
        if expected_row_size is None:
            expected_row_size = row_size # assume all same size as 1st row
        elif row_size != expected_row_size:
            raise ValueError('Expected {} things but found {}  on line# {}'.format(expected_row_size,row_size,line_cnt))
        print('line_cnt={} #things={}, line="{}"'.format(line_cnt, len(things), line))
         # read about append vs extend here https://stackoverflow.com/q/252703/5590742
        temp_row.extend(things)
        # check with %, the mod operator, 1%3 = 1, 2%3 = 2, 3%3 = 0 (even division), 4%3 = 1, 5%3 = 2, etc.
        # We're counting lines from 1, so if we get zero we have that many lines
        if 0 == (line_cnt % nrows):
            print('gathered {} into={}'.format(nrows,temp_row))
            # or write gathered to another file
            consolidated_rows.append(temp_row)
            temp_row = [ ] # start a new list
    if temp_row:
        # at end of file, but make sure we include partial results
        # (if you expect perfect alignment this would
        # be another good place for an error check.)
        consolidated_rows.append(temp_row)
    return consolidated_rows
test_lines="""a b c
d e f
g h i
j k l
m n o
p q r
s t v
u w x
y z 0
1 2 3
4 5 6
7 8 9"""
# if your data is in a file use:
# with open('myfile.txt', 'r') as f:
with io.StringIO(test_lines) as f:
    rows = join_dataset(f, nrows=3)
    # rows = join_dataset(f) # this will default to nrows=10
print('now have {} rows'.format(len(rows)))
print('rows={}'.format('n'.join([str(row) for row in rows])))

我知道你用Python标记了你的问题,但这里有一个命令行方法可以做到这一点:

xargs -n10 -d'n' < yourlistfile.txt

其中yourlistfile.txt是要分析的文件的名称。

所写的命令将输出到屏幕。 您可以通过将其添加到该命令的末尾来将该输出重定向到新文件:> your_results.txt,例如:

xargs -n10 -d'n' < yourlistfile.txt > reorganizedlistfile.txt

在这篇文章中查看其他一些想法:如何从命令行将每两行合并为一行?

注意:显然某些版本的xargs不喜欢该-d选项,例如,我在MacOS上收到错误,指出该选项不受支持。 但是对于用硬回车分隔标记的简单示例,无论如何都不需要分隔符参数。

最新更新