Pipes实现LeetCode(194.转置文件)

[LeetCode] 194.Transpose File 转置文件

Given a text file file.txt, transpose its content.

You may assume that each row has the same number of columns and each field is separated by the ' ' character.

For example, if file.txt has the following content:

name age
alice 21
ryan 30

Output the following:

name alice ryan
age 21 30

这道题让我们转置一个文件,其实感觉就是把文本内容当做了一个矩阵,每个单词空格隔开看做是矩阵中的一个元素,然后将转置后的内容打印出来。那么我们先来看使用awk关键字的做法。其中NF表示当前记录中的字段个数,就是有多少列,NR表示已经读出的记录数,就是行号,从1开始。那么在这里NF是2,因为文本只有两列,这里面这个for循环还跟我们通常所熟悉for循环不太一样,通常我们以为i只能是1和2,然后循环就结束了,而这里的i实际上遍历的数字为1,2,1,2,1,2,我们可能看到实际上循环了3遍1和2,而行数正好是3,可能人家就是这个机制吧。知道了上面这些,那么下面的代码就不难理解了,遍历过程如下:

i = 1, s = [name]

i = 2, s = [name; age]

i = 1, s = [name alice; age]

i = 2, s = [name alice; age 21]

i = 1, s = [name alice ryan; age 21]

i = 2, s = [name alice ryan; age 21 30]

然后我们再将s中的各行打印出来即可,参见代码如下:

解法一:

awk '{
    for (i = 1; i <= NF; ++i) {
        if (NR == 1) s[i] = $i;
        else s[i] = s[i] " " $i;
    }
} END {
    for (i = 1; s[i] != ""; ++i) {
        print s[i];
    }
}' file.txt

下面这种方法和上面的思路完全一样,但是代码风格不一样,上面是C语言风格,而这个完全就是Bash脚本的风格了,我们用read关键字,我们可以查看read的用法read: usage: read [-ers] [-u fd] [-t timeout] [-p prompt] [-a array] [-n nchars] [-d delim] [name ...]。那么我们知道-a表示数组,将读出的每行内容存入数组line中,那么下一行for中的一堆特殊字符肯定让你头晕眼花,其实我也不能算特别理解下面的代码,大概觉得跟上面的思路一样,求大神来具体给讲解下哈:

解法二:

while read -a line; do
    for ((i = 0; i < "${#line[@]}"; ++i)); do
        a[$i]="${a[$i]} ${line[$i]}"
    done
done < file.txt
for ((i = 0; i < ${#a[@]}; ++i)); do
    echo ${a[i]}
done

参考资料:

https://leetcode.com/problems/transpose-file/

https://leetcode.com/problems/transpose-file/discuss/55522/AC-Solution%3A-8-lines-only-in-pure-Bash

https://leetcode.com/problems/transpose-file/discuss/55502/AC-solution-using-awk-and-statement-just-like-C.

到此这篇关于Pipes实现LeetCode(194.转置文件)的文章就介绍到这了,更多相关Pipes实现转置文件内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Pipes实现LeetCode(192.单词频率)

    [LeetCode] 192.Word Frequency 单词频率 Write a bash script to calculate the frequency of each word in a text file words.txt. For simplicity sake, you may assume: words.txt contains only lowercase characters and space ' ' characters. Each word must consis

  • C++实现LeetCode(191.位1的个数)

    [LeetCode] 191.Number of 1 Bits 位1的个数 Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). For example, the 32-bit integer '11' has binary representation 00000000000000000000000

  • Pipes实现LeetCode(195.第十行)

    [LeetCode] 195.Tenth Line 第十行 How would you print just the 10th line of a file? For example, assume that file.txt has the following content: Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10 Your script should output the tenth li

  • C++实现LeetCode(186.翻转字符串中的单词之二)

    [LeetCode] 186. Reverse Words in a String II 翻转字符串中的单词之二 Given an input string , reverse the string word by word.  Example: Input:  ["t","h","e"," ","s","k","y"," ","i&qu

  • C++实现LeetCode(557.翻转字符串中的单词之三)

    [LeetCode] 557.Reverse Words in a String III 翻转字符串中的单词之三 Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: "Let's take LeetCode conte

  • C++实现LeetCode(190.颠倒二进制位)

    [LeetCode] 190. Reverse Bits 颠倒二进制位 Reverse bits of a given 32 bits unsigned integer. Example 1: Input: 00000010100101000001111010011100 Output: 00111001011110000010100101000000 Explanation: The input binary string 00000010100101000001111010011100 re

  • C++实现LeetCode(309.买股票的最佳时间含冷冻期)

    [LeetCode] 309.Best Time to Buy and Sell Stock with Cooldown 买股票的最佳时间含冷冻期 Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as

  • C++实现LeetCode(188.买卖股票的最佳时间之四)

    [LeetCode] 188.Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四 Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most k transactions. Note: You m

  • Pipes实现LeetCode(194.转置文件)

    [LeetCode] 194.Transpose File 转置文件 Given a text file file.txt, transpose its content. You may assume that each row has the same number of columns and each field is separated by the ' ' character. For example, if file.txt has the following content: na

  • Pipes实现LeetCode(193.验证电话号码)

    [LeetCode] 193.Valid Phone Numbers 验证电话号码 Given a text file file.txt that contains list of phone numbers (one per line), write a one liner bash script to print all valid phone numbers. You may assume that a valid phone number must appear in one of th

  • Python常用模块介绍

    python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的. 常用的libraries(modules)如下: 1)python运行时服务 * copy: copy模块提供了对复合(compound)对象(list,tuple,dict,custom class)进行浅拷贝和深拷贝的功能. * pickle: pickle模块被用来序列化python的对象到bytes流,从而适合存储到文件,网络传输,或数据库存

  • Python中xlsx文件转置操作详解(行转列和列转行)

    目录 1.原始数据是这样的 2.脚本如下: 3.运行脚本后生成的xlsx文件,如下: 附:pivot方法即可完成行转列哦 总结 1.原始数据是这样的 2.脚本如下: import pandas as pd df = pd.read_excel(r'E:\untitled1\带宽测试\temp.xlsx') # 读取需要转置的文件 df = df.T # 转置 df.to_excel(r'E:\untitled1\带宽测试\TestResult.xlsx') # 另存为xlsx文件 3.运行脚本后

  • Go语言LeetCode题解937重新排列日志文件

    目录 一 题目描述 二 分析 三 答案 一 题目描述 937. 重新排列日志文件 - 力扣(LeetCode) (leetcode-cn.com) 给你一个日志数组 logs.每条日志都是以空格分隔的字串,其第一个字为字母与数字混合的 标识符 . 有两种不同类型的日志: 字母日志:除标识符之外,所有字均由小写字母组成 数字日志:除标识符之外,所有字均由数字组成 请按下述规则将日志重新排序: 所有 字母日志 都排在 数字日志 之前. 字母日志 在内容不同时,忽略标识符后,按内容字母顺序排序:在内容

  • Python使用openpyxl读写excel文件的方法

    这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取Excel文件 需要导入相关函数. from openpyxl import load_workbook # 默认可读写,若有需要可以指定write_only和read_only为True wb = load_workbook('mainbuilding33.xlsx') 默认打开的文件为可读写,若有需要可以指定参数read_only为True. 获取

  • java实现二维数组转置的方法示例

    本文实例讲述了java实现二维数组转置的方法.分享给大家供大家参考,具体如下: 这里在文件中创建Test2.Exchange.Out三个类 在Exchange类中编写exchange()方法,在方法中创建两个数组arraryA.arraryB,arraryB[j][i]=arraryA[i][j]实现数组的转置. 在Out类中编写out()方法,在方法中用for循环遍历实现输出. 具体代码如下: package Tsets; import java.util.*; public class Te

  • jQuery实现简单的文件上传进度条效果

    本文实例讲述了jQuery实现文件上传进度条效果的代码.分享给大家供大家参考.具体如下: 运行效果截图如下: 具体代码如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>upload</title> <link rel="stylesheet" type="text/css" href=&quo

随机推荐